pocketpy.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  1. #include "pocketpy/pocketpy.h"
  2. #ifdef PK_USE_BOX2D
  3. #include "box2dw.hpp"
  4. #endif
  5. #ifdef PK_USE_CJSON
  6. #include "cJSONw.hpp"
  7. #endif
  8. namespace pkpy{
  9. void init_builtins(VM* _vm) {
  10. #define BIND_NUM_ARITH_OPT(name, op) \
  11. _vm->bind##name(_vm->tp_int, [](VM* vm, PyObject* lhs, PyObject* rhs) { \
  12. if(is_int(rhs)) return VAR(_CAST(i64, lhs) op _CAST(i64, rhs)); \
  13. if(is_float(rhs)) return VAR(_CAST(i64, lhs) op _CAST(f64, rhs)); \
  14. return vm->NotImplemented; \
  15. }); \
  16. _vm->bind##name(_vm->tp_float, [](VM* vm, PyObject* lhs, PyObject* rhs) { \
  17. if(is_float(rhs)) return VAR(_CAST(f64, lhs) op _CAST(f64, rhs)); \
  18. if(is_int(rhs)) return VAR(_CAST(f64, lhs) op _CAST(i64, rhs)); \
  19. return vm->NotImplemented; \
  20. });
  21. BIND_NUM_ARITH_OPT(__add__, +)
  22. BIND_NUM_ARITH_OPT(__sub__, -)
  23. BIND_NUM_ARITH_OPT(__mul__, *)
  24. #undef BIND_NUM_ARITH_OPT
  25. #define BIND_NUM_LOGICAL_OPT(name, op) \
  26. _vm->bind##name(_vm->tp_int, [](VM* vm, PyObject* lhs, PyObject* rhs) { \
  27. i64 val; \
  28. if(try_cast_int(rhs, &val)) return VAR(_CAST(i64, lhs) op val); \
  29. if(is_float(rhs)) return VAR(_CAST(i64, lhs) op _CAST(f64, rhs)); \
  30. return vm->NotImplemented; \
  31. }); \
  32. _vm->bind##name(_vm->tp_float, [](VM* vm, PyObject* lhs, PyObject* rhs) { \
  33. i64 val; \
  34. if(try_cast_int(rhs, &val)) return VAR(_CAST(f64, lhs) op val); \
  35. if(is_float(rhs)) return VAR(_CAST(f64, lhs) op _CAST(f64, rhs)); \
  36. return vm->NotImplemented; \
  37. });
  38. BIND_NUM_LOGICAL_OPT(__eq__, ==)
  39. BIND_NUM_LOGICAL_OPT(__lt__, <)
  40. BIND_NUM_LOGICAL_OPT(__le__, <=)
  41. BIND_NUM_LOGICAL_OPT(__gt__, >)
  42. BIND_NUM_LOGICAL_OPT(__ge__, >=)
  43. #undef BIND_NUM_ARITH_OPT
  44. #undef BIND_NUM_LOGICAL_OPT
  45. _vm->bind_builtin_func<-1>("super", [](VM* vm, ArgsView args) {
  46. PyObject* class_arg = nullptr;
  47. PyObject* self_arg = nullptr;
  48. if(args.size() == 2){
  49. class_arg = args[0];
  50. self_arg = args[1];
  51. }else if(args.size() == 0){
  52. FrameId frame = vm->top_frame();
  53. if(frame->_callable != nullptr){
  54. class_arg = PK_OBJ_GET(Function, frame->_callable)._class;
  55. if(frame->_locals.size() > 0) self_arg = frame->_locals[0];
  56. }
  57. if(class_arg == nullptr || self_arg == nullptr){
  58. vm->TypeError("super(): unable to determine the class context, use super(class, self) instead");
  59. }
  60. }else{
  61. vm->TypeError("super() takes 0 or 2 arguments");
  62. }
  63. vm->check_non_tagged_type(class_arg, vm->tp_type);
  64. Type type = PK_OBJ_GET(Type, class_arg);
  65. if(!vm->isinstance(self_arg, type)){
  66. StrName _0 = obj_type_name(vm, vm->_tp(self_arg));
  67. StrName _1 = obj_type_name(vm, type);
  68. vm->TypeError("super(): " + _0.escape() + " is not an instance of " + _1.escape());
  69. }
  70. return vm->heap.gcnew<Super>(vm->tp_super, self_arg, vm->_all_types[type].base);
  71. });
  72. _vm->bind_builtin_func<2>("isinstance", [](VM* vm, ArgsView args) {
  73. if(is_non_tagged_type(args[1], vm->tp_tuple)){
  74. Tuple& types = _CAST(Tuple&, args[1]);
  75. for(PyObject* type : types){
  76. vm->check_non_tagged_type(type, vm->tp_type);
  77. if(vm->isinstance(args[0], PK_OBJ_GET(Type, type))) return vm->True;
  78. }
  79. return vm->False;
  80. }
  81. vm->check_non_tagged_type(args[1], vm->tp_type);
  82. Type type = PK_OBJ_GET(Type, args[1]);
  83. return VAR(vm->isinstance(args[0], type));
  84. });
  85. _vm->bind_builtin_func<0>("globals", [](VM* vm, ArgsView args) {
  86. PyObject* mod = vm->top_frame()->_module;
  87. return VAR(MappingProxy(mod));
  88. });
  89. _vm->bind(_vm->builtins, "round(x, ndigits=0)", [](VM* vm, ArgsView args) {
  90. f64 x = CAST(f64, args[0]);
  91. int ndigits = CAST(int, args[1]);
  92. if(ndigits == 0){
  93. return x >= 0 ? VAR((i64)(x + 0.5)) : VAR((i64)(x - 0.5));
  94. }
  95. if(ndigits < 0) vm->ValueError("ndigits should be non-negative");
  96. if(x >= 0){
  97. return VAR((i64)(x * std::pow(10, ndigits) + 0.5) / std::pow(10, ndigits));
  98. }else{
  99. return VAR((i64)(x * std::pow(10, ndigits) - 0.5) / std::pow(10, ndigits));
  100. }
  101. });
  102. _vm->bind_builtin_func<1>("abs", [](VM* vm, ArgsView args) {
  103. if(is_int(args[0])) return VAR(std::abs(_CAST(i64, args[0])));
  104. if(is_float(args[0])) return VAR(std::abs(_CAST(f64, args[0])));
  105. vm->TypeError("bad operand type for abs()");
  106. return vm->None;
  107. });
  108. _vm->bind_builtin_func<1>("id", [](VM* vm, ArgsView args) {
  109. PyObject* obj = args[0];
  110. if(is_tagged(obj)) return vm->None;
  111. return VAR(PK_BITS(obj));
  112. });
  113. _vm->bind_builtin_func<1>("callable", [](VM* vm, ArgsView args) {
  114. PyObject* cls = vm->_t(args[0]);
  115. Type t = PK_OBJ_GET(Type, cls);
  116. if(t == vm->tp_function) return vm->True;
  117. if(t == vm->tp_native_func) return vm->True;
  118. if(t == vm->tp_bound_method) return vm->True;
  119. if(t == vm->tp_type) return vm->True;
  120. bool ok = vm->find_name_in_mro(cls, __call__) != nullptr;
  121. return VAR(ok);
  122. });
  123. _vm->bind_builtin_func<1>("__import__", [](VM* vm, ArgsView args) {
  124. const Str& name = CAST(Str&, args[0]);
  125. return vm->py_import(name);
  126. });
  127. _vm->bind_builtin_func<2>("divmod", [](VM* vm, ArgsView args) {
  128. if(is_int(args[0])){
  129. i64 lhs = _CAST(i64, args[0]);
  130. i64 rhs = CAST(i64, args[1]);
  131. if(rhs == 0) vm->ZeroDivisionError();
  132. auto res = std::div(lhs, rhs);
  133. return VAR(Tuple({VAR(res.quot), VAR(res.rem)}));
  134. }else{
  135. return vm->call_method(args[0], __divmod__, args[1]);
  136. }
  137. });
  138. _vm->bind(_vm->builtins, "eval(__source, __globals=None)", [](VM* vm, ArgsView args) {
  139. CodeObject_ code = vm->compile(CAST(Str&, args[0]), "<eval>", EVAL_MODE, true);
  140. PyObject* globals = args[1];
  141. if(globals == vm->None){
  142. FrameId frame = vm->top_frame();
  143. return vm->_exec(code.get(), frame->_module, frame->_callable, frame->_locals);
  144. }
  145. vm->check_non_tagged_type(globals, vm->tp_mappingproxy);
  146. PyObject* obj = PK_OBJ_GET(MappingProxy, globals).obj;
  147. return vm->_exec(code, obj);
  148. });
  149. _vm->bind(_vm->builtins, "exec(__source, __globals=None)", [](VM* vm, ArgsView args) {
  150. CodeObject_ code = vm->compile(CAST(Str&, args[0]), "<exec>", EXEC_MODE, true);
  151. PyObject* globals = args[1];
  152. if(globals == vm->None){
  153. FrameId frame = vm->top_frame();
  154. vm->_exec(code.get(), frame->_module, frame->_callable, frame->_locals);
  155. return vm->None;
  156. }
  157. vm->check_non_tagged_type(globals, vm->tp_mappingproxy);
  158. PyObject* obj = PK_OBJ_GET(MappingProxy, globals).obj;
  159. vm->_exec(code, obj);
  160. return vm->None;
  161. });
  162. _vm->bind_builtin_func<-1>("exit", [](VM* vm, ArgsView args) {
  163. if(args.size() == 0) std::exit(0);
  164. else if(args.size() == 1) std::exit(CAST(int, args[0]));
  165. else vm->TypeError("exit() takes at most 1 argument");
  166. return vm->None;
  167. });
  168. _vm->bind_builtin_func<1>("repr", PK_LAMBDA(vm->py_repr(args[0])));
  169. _vm->bind_builtin_func<1>("len", [](VM* vm, ArgsView args){
  170. const PyTypeInfo* ti = vm->_inst_type_info(args[0]);
  171. if(ti->m__len__) return VAR(ti->m__len__(vm, args[0]));
  172. return vm->call_method(args[0], __len__);
  173. });
  174. _vm->bind_builtin_func<1>("hash", [](VM* vm, ArgsView args){
  175. i64 value = vm->py_hash(args[0]);
  176. return VAR(value);
  177. });
  178. _vm->bind_builtin_func<1>("chr", [](VM* vm, ArgsView args) {
  179. i64 i = CAST(i64, args[0]);
  180. if (i < 0 || i > 128) vm->ValueError("chr() arg not in range(128)");
  181. return VAR(std::string(1, (char)i));
  182. });
  183. _vm->bind_builtin_func<1>("ord", [](VM* vm, ArgsView args) {
  184. const Str& s = CAST(Str&, args[0]);
  185. if (s.length()!=1) vm->TypeError("ord() expected an ASCII character");
  186. return VAR((i64)(s[0]));
  187. });
  188. _vm->bind_builtin_func<2>("hasattr", [](VM* vm, ArgsView args) {
  189. return VAR(vm->getattr(args[0], CAST(Str&, args[1]), false) != nullptr);
  190. });
  191. _vm->bind_builtin_func<3>("setattr", [](VM* vm, ArgsView args) {
  192. vm->setattr(args[0], CAST(Str&, args[1]), args[2]);
  193. return vm->None;
  194. });
  195. _vm->bind_builtin_func<2>("getattr", [](VM* vm, ArgsView args) {
  196. const Str& name = CAST(Str&, args[1]);
  197. return vm->getattr(args[0], name);
  198. });
  199. _vm->bind_builtin_func<2>("delattr", [](VM* vm, ArgsView args) {
  200. vm->delattr(args[0], CAST(Str&, args[1]));
  201. return vm->None;
  202. });
  203. _vm->bind_builtin_func<1>("hex", [](VM* vm, ArgsView args) {
  204. std::stringstream ss; // hex
  205. ss << std::hex << CAST(i64, args[0]);
  206. return VAR("0x" + ss.str());
  207. });
  208. _vm->bind_builtin_func<1>("iter", [](VM* vm, ArgsView args) {
  209. return vm->py_iter(args[0]);
  210. });
  211. _vm->bind_builtin_func<1>("next", [](VM* vm, ArgsView args) {
  212. return vm->py_next(args[0]);
  213. });
  214. _vm->bind_builtin_func<1>("bin", [](VM* vm, ArgsView args) {
  215. SStream ss;
  216. i64 x = CAST(i64, args[0]);
  217. if(x < 0){ ss << "-"; x = -x; }
  218. ss << "0b";
  219. std::string bits;
  220. while(x){
  221. bits += (x & 1) ? '1' : '0';
  222. x >>= 1;
  223. }
  224. std::reverse(bits.begin(), bits.end());
  225. if(bits.empty()) bits = "0";
  226. ss << bits;
  227. return VAR(ss.str());
  228. });
  229. _vm->bind_builtin_func<1>("dir", [](VM* vm, ArgsView args) {
  230. std::set<StrName> names;
  231. if(!is_tagged(args[0]) && args[0]->is_attr_valid()){
  232. std::vector<StrName> keys = args[0]->attr().keys();
  233. names.insert(keys.begin(), keys.end());
  234. }
  235. const NameDict& t_attr = vm->_t(args[0])->attr();
  236. std::vector<StrName> keys = t_attr.keys();
  237. names.insert(keys.begin(), keys.end());
  238. List ret;
  239. for (StrName name : names) ret.push_back(VAR(name.sv()));
  240. return VAR(std::move(ret));
  241. });
  242. _vm->bind__repr__(_vm->tp_object, [](VM* vm, PyObject* obj) {
  243. if(is_tagged(obj)) FATAL_ERROR();
  244. std::stringstream ss; // hex
  245. ss << "<" << OBJ_NAME(vm->_t(obj)) << " object at 0x";
  246. ss << std::hex << reinterpret_cast<intptr_t>(obj) << ">";
  247. return VAR(ss.str());
  248. });
  249. _vm->bind__eq__(_vm->tp_object, [](VM* vm, PyObject* lhs, PyObject* rhs) { return VAR(lhs == rhs); });
  250. _vm->cached_object__new__ = _vm->bind_constructor<1>("object", [](VM* vm, ArgsView args) {
  251. vm->check_non_tagged_type(args[0], vm->tp_type);
  252. Type t = PK_OBJ_GET(Type, args[0]);
  253. return vm->heap.gcnew<DummyInstance>(t);
  254. });
  255. _vm->bind_method<0>("object", "_enable_instance_dict", [](VM* vm, ArgsView args){
  256. PyObject* self = args[0];
  257. if(is_tagged(self)){
  258. vm->TypeError("object: tagged object cannot enable instance dict");
  259. }
  260. if(self->is_attr_valid()){
  261. vm->TypeError("object: instance dict is already enabled");
  262. }
  263. self->_enable_instance_dict();
  264. return vm->None;
  265. });
  266. _vm->bind_constructor<2>("type", PK_LAMBDA(vm->_t(args[1])));
  267. _vm->bind_constructor<-1>("range", [](VM* vm, ArgsView args) {
  268. args._begin += 1; // skip cls
  269. Range r;
  270. switch (args.size()) {
  271. case 1: r.stop = CAST(i64, args[0]); break;
  272. case 2: r.start = CAST(i64, args[0]); r.stop = CAST(i64, args[1]); break;
  273. case 3: r.start = CAST(i64, args[0]); r.stop = CAST(i64, args[1]); r.step = CAST(i64, args[2]); break;
  274. default: vm->TypeError("expected 1-3 arguments, got " + std::to_string(args.size()));
  275. }
  276. return VAR(r);
  277. });
  278. _vm->bind__iter__(_vm->tp_range, [](VM* vm, PyObject* obj) { return VAR_T(RangeIter, PK_OBJ_GET(Range, obj)); });
  279. _vm->bind__repr__(_vm->_type("NoneType"), [](VM* vm, PyObject* obj) { return VAR("None"); });
  280. _vm->bind__truediv__(_vm->tp_float, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  281. f64 value = CAST_F(rhs);
  282. return VAR(_CAST(f64, lhs) / value);
  283. });
  284. _vm->bind__truediv__(_vm->tp_int, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  285. f64 value = CAST_F(rhs);
  286. return VAR(_CAST(i64, lhs) / value);
  287. });
  288. auto py_number_pow = [](VM* vm, PyObject* lhs_, PyObject* rhs_) {
  289. i64 lhs, rhs;
  290. if(try_cast_int(lhs_, &lhs) && try_cast_int(rhs_, &rhs)){
  291. if(rhs < 0) {
  292. if(lhs == 0) vm->ZeroDivisionError("0.0 cannot be raised to a negative power");
  293. return VAR((f64)std::pow(lhs, rhs));
  294. }
  295. i64 ret = 1;
  296. while(rhs){
  297. if(rhs & 1) ret *= lhs;
  298. lhs *= lhs;
  299. rhs >>= 1;
  300. }
  301. return VAR(ret);
  302. }else{
  303. return VAR((f64)std::pow(CAST_F(lhs_), CAST_F(rhs_)));
  304. }
  305. };
  306. _vm->bind__pow__(_vm->tp_int, py_number_pow);
  307. _vm->bind__pow__(_vm->tp_float, py_number_pow);
  308. /************ int ************/
  309. _vm->bind_constructor<-1>("int", [](VM* vm, ArgsView args) {
  310. if(args.size() == 1+0) return VAR(0);
  311. // 1 arg
  312. if(args.size() == 1+1){
  313. if (is_type(args[1], vm->tp_float)) return VAR((i64)CAST(f64, args[1]));
  314. if (is_type(args[1], vm->tp_int)) return args[1];
  315. if (is_type(args[1], vm->tp_bool)) return VAR(_CAST(bool, args[1]) ? 1 : 0);
  316. }
  317. if(args.size() > 1+2) vm->TypeError("int() takes at most 2 arguments");
  318. // 2 args
  319. if (is_type(args[1], vm->tp_str)) {
  320. int base = 10;
  321. if(args.size() == 1+2) base = CAST(i64, args[2]);
  322. const Str& s = CAST(Str&, args[1]);
  323. i64 val;
  324. if(!parse_int(s.sv(), &val, base)){
  325. vm->ValueError("invalid literal for int(): " + s.escape());
  326. }
  327. return VAR(val);
  328. }
  329. vm->TypeError("invalid arguments for int()");
  330. return vm->None;
  331. });
  332. _vm->bind_method<0>("int", "bit_length", [](VM* vm, ArgsView args) {
  333. i64 x = _CAST(i64, args[0]);
  334. if(x < 0) x = -x;
  335. int bits = 0;
  336. while(x){ x >>= 1; bits++; }
  337. return VAR(bits);
  338. });
  339. _vm->bind__floordiv__(_vm->tp_int, [](VM* vm, PyObject* lhs_, PyObject* rhs_) {
  340. i64 rhs = CAST(i64, rhs_);
  341. if(rhs == 0) vm->ZeroDivisionError();
  342. return VAR(_CAST(i64, lhs_) / rhs);
  343. });
  344. _vm->bind__mod__(_vm->tp_int, [](VM* vm, PyObject* lhs_, PyObject* rhs_) {
  345. i64 rhs = CAST(i64, rhs_);
  346. if(rhs == 0) vm->ZeroDivisionError();
  347. return VAR(_CAST(i64, lhs_) % rhs);
  348. });
  349. _vm->bind__repr__(_vm->tp_int, [](VM* vm, PyObject* obj) { return VAR(std::to_string(_CAST(i64, obj))); });
  350. _vm->bind__neg__(_vm->tp_int, [](VM* vm, PyObject* obj) { return VAR(-_CAST(i64, obj)); });
  351. _vm->bind__hash__(_vm->tp_int, [](VM* vm, PyObject* obj) { return _CAST(i64, obj); });
  352. _vm->bind__invert__(_vm->tp_int, [](VM* vm, PyObject* obj) { return VAR(~_CAST(i64, obj)); });
  353. #define INT_BITWISE_OP(name, op) \
  354. _vm->bind##name(_vm->tp_int, [](VM* vm, PyObject* lhs, PyObject* rhs) { \
  355. return VAR(_CAST(i64, lhs) op CAST(i64, rhs)); \
  356. });
  357. INT_BITWISE_OP(__lshift__, <<)
  358. INT_BITWISE_OP(__rshift__, >>)
  359. INT_BITWISE_OP(__and__, &)
  360. INT_BITWISE_OP(__or__, |)
  361. INT_BITWISE_OP(__xor__, ^)
  362. #undef INT_BITWISE_OP
  363. /************ float ************/
  364. _vm->bind_constructor<-1>("float", [](VM* vm, ArgsView args) {
  365. if(args.size() == 1+0) return VAR(0.0);
  366. if(args.size() > 1+1) vm->TypeError("float() takes at most 1 argument");
  367. // 1 arg
  368. if (is_type(args[1], vm->tp_int)) return VAR((f64)CAST(i64, args[1]));
  369. if (is_type(args[1], vm->tp_float)) return args[1];
  370. if (is_type(args[1], vm->tp_bool)) return VAR(_CAST(bool, args[1]) ? 1.0 : 0.0);
  371. if (is_type(args[1], vm->tp_str)) {
  372. const Str& s = CAST(Str&, args[1]);
  373. if(s == "inf") return VAR(INFINITY);
  374. if(s == "-inf") return VAR(-INFINITY);
  375. double float_out;
  376. char* p_end;
  377. try{
  378. float_out = std::strtod(s.data, &p_end);
  379. PK_ASSERT(p_end == s.end());
  380. }catch(...){
  381. vm->ValueError("invalid literal for float(): " + s.escape());
  382. }
  383. return VAR(float_out);
  384. }
  385. vm->TypeError("invalid arguments for float()");
  386. return vm->None;
  387. });
  388. _vm->bind__hash__(_vm->tp_float, [](VM* vm, PyObject* obj) {
  389. f64 val = _CAST(f64, obj);
  390. return (i64)std::hash<f64>()(val);
  391. });
  392. _vm->bind__neg__(_vm->tp_float, [](VM* vm, PyObject* obj) { return VAR(-_CAST(f64, obj)); });
  393. _vm->bind__repr__(_vm->tp_float, [](VM* vm, PyObject* obj) {
  394. f64 val = _CAST(f64, obj);
  395. SStream ss;
  396. ss << val;
  397. return VAR(ss.str());
  398. });
  399. /************ str ************/
  400. _vm->bind_constructor<2>("str", PK_LAMBDA(vm->py_str(args[1])));
  401. _vm->bind__hash__(_vm->tp_str, [](VM* vm, PyObject* obj) {
  402. return (i64)_CAST(Str&, obj).hash();
  403. });
  404. _vm->bind__add__(_vm->tp_str, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  405. return VAR(_CAST(Str&, lhs) + CAST(Str&, rhs));
  406. });
  407. _vm->bind__len__(_vm->tp_str, [](VM* vm, PyObject* obj) {
  408. return (i64)_CAST(Str&, obj).u8_length();
  409. });
  410. _vm->bind__mul__(_vm->tp_str, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  411. const Str& self = _CAST(Str&, lhs);
  412. i64 n = CAST(i64, rhs);
  413. SStream ss;
  414. for(i64 i = 0; i < n; i++) ss << self.sv();
  415. return VAR(ss.str());
  416. });
  417. _vm->bind_method<1>("str", "__rmul__", [](VM* vm, ArgsView args) {
  418. const Str& self = _CAST(Str&, args[0]);
  419. i64 n = CAST(i64, args[1]);
  420. SStream ss;
  421. for(i64 i = 0; i < n; i++) ss << self.sv();
  422. return VAR(ss.str());
  423. });
  424. _vm->bind__contains__(_vm->tp_str, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  425. const Str& self = _CAST(Str&, lhs);
  426. return VAR(self.index(CAST(Str&, rhs)) != -1);
  427. });
  428. _vm->bind__str__(_vm->tp_str, [](VM* vm, PyObject* obj) { return obj; });
  429. _vm->bind__iter__(_vm->tp_str, [](VM* vm, PyObject* obj) { return VAR_T(StringIter, obj); });
  430. _vm->bind__repr__(_vm->tp_str, [](VM* vm, PyObject* obj) {
  431. const Str& self = _CAST(Str&, obj);
  432. return VAR(self.escape(true));
  433. });
  434. #define BIND_CMP_STR(name, op) \
  435. _vm->bind##name(_vm->tp_str, [](VM* vm, PyObject* lhs, PyObject* rhs) { \
  436. if(!is_non_tagged_type(rhs, vm->tp_str)) return vm->NotImplemented; \
  437. return VAR(_CAST(Str&, lhs) op _CAST(Str&, rhs)); \
  438. });
  439. BIND_CMP_STR(__eq__, ==)
  440. BIND_CMP_STR(__lt__, <)
  441. BIND_CMP_STR(__le__, <=)
  442. BIND_CMP_STR(__gt__, >)
  443. BIND_CMP_STR(__ge__, >=)
  444. #undef BIND_CMP_STR
  445. _vm->bind__getitem__(_vm->tp_str, [](VM* vm, PyObject* obj, PyObject* index) {
  446. const Str& self = _CAST(Str&, obj);
  447. if(is_non_tagged_type(index, vm->tp_slice)){
  448. const Slice& s = _CAST(Slice&, index);
  449. int start, stop, step;
  450. vm->parse_int_slice(s, self.u8_length(), start, stop, step);
  451. return VAR(self.u8_slice(start, stop, step));
  452. }
  453. int i = CAST(int, index);
  454. i = vm->normalized_index(i, self.u8_length());
  455. return VAR(self.u8_getitem(i));
  456. });
  457. _vm->bind(_vm->_t(_vm->tp_str), "replace(self, old, new, count=-1)", [](VM* vm, ArgsView args) {
  458. const Str& self = _CAST(Str&, args[0]);
  459. const Str& old = CAST(Str&, args[1]);
  460. if(old.empty()) vm->ValueError("empty substring");
  461. const Str& new_ = CAST(Str&, args[2]);
  462. int count = CAST(int, args[3]);
  463. return VAR(self.replace(old, new_, count));
  464. });
  465. _vm->bind(_vm->_t(_vm->tp_str), "split(self, sep=' ')", [](VM* vm, ArgsView args) {
  466. const Str& self = _CAST(Str&, args[0]);
  467. const Str& sep = CAST(Str&, args[1]);
  468. if(sep.empty()) vm->ValueError("empty separator");
  469. std::vector<std::string_view> parts;
  470. if(sep.size == 1){
  471. parts = self.split(sep[0]);
  472. }else{
  473. parts = self.split(sep);
  474. }
  475. List ret(parts.size());
  476. for(int i=0; i<parts.size(); i++) ret[i] = VAR(Str(parts[i]));
  477. return VAR(std::move(ret));
  478. });
  479. _vm->bind(_vm->_t(_vm->tp_str), "splitlines(self)", [](VM* vm, ArgsView args) {
  480. const Str& self = _CAST(Str&, args[0]);
  481. std::vector<std::string_view> parts;
  482. parts = self.split('\n');
  483. List ret(parts.size());
  484. for(int i=0; i<parts.size(); i++) ret[i] = VAR(Str(parts[i]));
  485. return VAR(std::move(ret));
  486. });
  487. _vm->bind(_vm->_t(_vm->tp_str), "count(self, s: str)", [](VM* vm, ArgsView args) {
  488. const Str& self = _CAST(Str&, args[0]);
  489. const Str& s = CAST(Str&, args[1]);
  490. return VAR(self.count(s));
  491. });
  492. _vm->bind_method<1>("str", "index", [](VM* vm, ArgsView args) {
  493. const Str& self = _CAST(Str&, args[0]);
  494. const Str& sub = CAST(Str&, args[1]);
  495. int index = self.index(sub);
  496. if(index == -1) vm->ValueError("substring not found");
  497. return VAR(index);
  498. });
  499. _vm->bind_method<1>("str", "find", [](VM* vm, ArgsView args) {
  500. const Str& self = _CAST(Str&, args[0]);
  501. const Str& sub = CAST(Str&, args[1]);
  502. return VAR(self.index(sub));
  503. });
  504. _vm->bind_method<1>("str", "startswith", [](VM* vm, ArgsView args) {
  505. const Str& self = _CAST(Str&, args[0]);
  506. const Str& prefix = CAST(Str&, args[1]);
  507. return VAR(self.index(prefix) == 0);
  508. });
  509. _vm->bind_method<1>("str", "endswith", [](VM* vm, ArgsView args) {
  510. const Str& self = _CAST(Str&, args[0]);
  511. const Str& suffix = CAST(Str&, args[1]);
  512. int offset = self.length() - suffix.length();
  513. if(offset < 0) return vm->False;
  514. bool ok = memcmp(self.data+offset, suffix.data, suffix.length()) == 0;
  515. return VAR(ok);
  516. });
  517. _vm->bind_method<0>("str", "encode", [](VM* vm, ArgsView args) {
  518. const Str& self = _CAST(Str&, args[0]);
  519. unsigned char* buffer = new unsigned char[self.length()];
  520. memcpy(buffer, self.data, self.length());
  521. return VAR(Bytes(buffer, self.length()));
  522. });
  523. _vm->bind_method<1>("str", "join", [](VM* vm, ArgsView args) {
  524. auto _lock = vm->heap.gc_scope_lock();
  525. const Str& self = _CAST(Str&, args[0]);
  526. SStream ss;
  527. PyObject* it = vm->py_iter(args[1]); // strong ref
  528. PyObject* obj = vm->py_next(it);
  529. while(obj != vm->StopIteration){
  530. if(!ss.empty()) ss << self;
  531. ss << CAST(Str&, obj);
  532. obj = vm->py_next(it);
  533. }
  534. return VAR(ss.str());
  535. });
  536. _vm->bind_method<0>("str", "lower", [](VM* vm, ArgsView args) {
  537. const Str& self = _CAST(Str&, args[0]);
  538. return VAR(self.lower());
  539. });
  540. _vm->bind_method<0>("str", "upper", [](VM* vm, ArgsView args) {
  541. const Str& self = _CAST(Str&, args[0]);
  542. return VAR(self.upper());
  543. });
  544. /************ list ************/
  545. _vm->bind(_vm->_t(_vm->tp_list), "sort(self, key=None, reverse=False)", [](VM* vm, ArgsView args) {
  546. List& self = _CAST(List&, args[0]);
  547. PyObject* key = args[1];
  548. if(key == vm->None){
  549. std::stable_sort(self.begin(), self.end(), [vm](PyObject* a, PyObject* b){
  550. return vm->py_lt(a, b);
  551. });
  552. }else{
  553. std::stable_sort(self.begin(), self.end(), [vm, key](PyObject* a, PyObject* b){
  554. return vm->py_lt(vm->call(key, a), vm->call(key, b));
  555. });
  556. }
  557. bool reverse = CAST(bool, args[2]);
  558. if(reverse) self.reverse();
  559. return vm->None;
  560. });
  561. _vm->bind__repr__(_vm->tp_list, [](VM* vm, PyObject* _0){
  562. List& iterable = _CAST(List&, _0);
  563. SStream ss;
  564. ss << '[';
  565. for(int i=0; i<iterable.size(); i++){
  566. ss << CAST(Str&, vm->py_repr(iterable[i]));
  567. if(i != iterable.size()-1) ss << ", ";
  568. }
  569. ss << ']';
  570. return VAR(ss.str());
  571. });
  572. _vm->bind__repr__(_vm->tp_tuple, [](VM* vm, PyObject* _0){
  573. Tuple& iterable = _CAST(Tuple&, _0);
  574. SStream ss;
  575. ss << '(';
  576. if(iterable.size() == 1){
  577. ss << CAST(Str&, vm->py_repr(iterable[0]));
  578. ss << ',';
  579. }else{
  580. for(int i=0; i<iterable.size(); i++){
  581. ss << CAST(Str&, vm->py_repr(iterable[i]));
  582. if(i != iterable.size()-1) ss << ", ";
  583. }
  584. }
  585. ss << ')';
  586. return VAR(ss.str());
  587. });
  588. _vm->bind_constructor<-1>("list", [](VM* vm, ArgsView args) {
  589. if(args.size() == 1+0) return VAR(List());
  590. if(args.size() == 1+1){
  591. return vm->py_list(args[1]);
  592. }
  593. vm->TypeError("list() takes 0 or 1 arguments");
  594. return vm->None;
  595. });
  596. _vm->bind__contains__(_vm->tp_list, [](VM* vm, PyObject* obj, PyObject* item) {
  597. List& self = _CAST(List&, obj);
  598. for(PyObject* i: self) if(vm->py_eq(i, item)) return vm->True;
  599. return vm->False;
  600. });
  601. _vm->bind_method<1>("list", "count", [](VM* vm, ArgsView args) {
  602. List& self = _CAST(List&, args[0]);
  603. int count = 0;
  604. for(PyObject* i: self) if(vm->py_eq(i, args[1])) count++;
  605. return VAR(count);
  606. });
  607. _vm->bind__eq__(_vm->tp_list, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  608. List& a = _CAST(List&, lhs);
  609. if(!is_non_tagged_type(rhs, vm->tp_list)) return vm->NotImplemented;
  610. List& b = _CAST(List&, rhs);
  611. if(a.size() != b.size()) return vm->False;
  612. for(int i=0; i<a.size(); i++){
  613. if(!vm->py_eq(a[i], b[i])) return vm->False;
  614. }
  615. return vm->True;
  616. });
  617. _vm->bind_method<1>("list", "index", [](VM* vm, ArgsView args) {
  618. List& self = _CAST(List&, args[0]);
  619. PyObject* obj = args[1];
  620. for(int i=0; i<self.size(); i++){
  621. if(vm->py_eq(self[i], obj)) return VAR(i);
  622. }
  623. vm->ValueError(_CAST(Str&, vm->py_repr(obj)) + " is not in list");
  624. return vm->None;
  625. });
  626. _vm->bind_method<1>("list", "remove", [](VM* vm, ArgsView args) {
  627. List& self = _CAST(List&, args[0]);
  628. PyObject* obj = args[1];
  629. for(int i=0; i<self.size(); i++){
  630. if(vm->py_eq(self[i], obj)){
  631. self.erase(i);
  632. return vm->None;
  633. }
  634. }
  635. vm->ValueError(_CAST(Str&, vm->py_repr(obj)) + " is not in list");
  636. return vm->None;
  637. });
  638. _vm->bind_method<-1>("list", "pop", [](VM* vm, ArgsView args) {
  639. List& self = _CAST(List&, args[0]);
  640. if(args.size() == 1+0){
  641. if(self.empty()) vm->IndexError("pop from empty list");
  642. return self.popx_back();
  643. }
  644. if(args.size() == 1+1){
  645. int index = CAST(int, args[1]);
  646. index = vm->normalized_index(index, self.size());
  647. PyObject* ret = self[index];
  648. self.erase(index);
  649. return ret;
  650. }
  651. vm->TypeError("pop() takes at most 1 argument");
  652. return vm->None;
  653. });
  654. _vm->bind_method<1>("list", "append", [](VM* vm, ArgsView args) {
  655. List& self = _CAST(List&, args[0]);
  656. self.push_back(args[1]);
  657. return vm->None;
  658. });
  659. _vm->bind_method<1>("list", "extend", [](VM* vm, ArgsView args) {
  660. auto _lock = vm->heap.gc_scope_lock();
  661. List& self = _CAST(List&, args[0]);
  662. PyObject* it = vm->py_iter(args[1]); // strong ref
  663. PyObject* obj = vm->py_next(it);
  664. while(obj != vm->StopIteration){
  665. self.push_back(obj);
  666. obj = vm->py_next(it);
  667. }
  668. return vm->None;
  669. });
  670. _vm->bind_method<0>("list", "reverse", [](VM* vm, ArgsView args) {
  671. List& self = _CAST(List&, args[0]);
  672. std::reverse(self.begin(), self.end());
  673. return vm->None;
  674. });
  675. _vm->bind__mul__(_vm->tp_list, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  676. const List& self = _CAST(List&, lhs);
  677. if(!is_int(rhs)) return vm->NotImplemented;
  678. int n = _CAST(int, rhs);
  679. List result;
  680. result.reserve(self.size() * n);
  681. for(int i = 0; i < n; i++) result.extend(self);
  682. return VAR(std::move(result));
  683. });
  684. _vm->bind_method<1>("list", "__rmul__", [](VM* vm, ArgsView args) {
  685. const List& self = _CAST(List&, args[0]);
  686. if(!is_int(args[1])) return vm->NotImplemented;
  687. int n = _CAST(int, args[1]);
  688. List result;
  689. result.reserve(self.size() * n);
  690. for(int i = 0; i < n; i++) result.extend(self);
  691. return VAR(std::move(result));
  692. });
  693. _vm->bind_method<2>("list", "insert", [](VM* vm, ArgsView args) {
  694. List& self = _CAST(List&, args[0]);
  695. int index = CAST(int, args[1]);
  696. if(index < 0) index += self.size();
  697. if(index < 0) index = 0;
  698. if(index > self.size()) index = self.size();
  699. self.insert(index, args[2]);
  700. return vm->None;
  701. });
  702. _vm->bind_method<0>("list", "clear", [](VM* vm, ArgsView args) {
  703. _CAST(List&, args[0]).clear();
  704. return vm->None;
  705. });
  706. _vm->bind_method<0>("list", "copy", PK_LAMBDA(VAR(_CAST(List, args[0]))));
  707. #define BIND_RICH_CMP(name, op, _t, _T) \
  708. _vm->bind__##name##__(_vm->_t, [](VM* vm, PyObject* lhs, PyObject* rhs){ \
  709. if(!is_non_tagged_type(rhs, vm->_t)) return vm->NotImplemented; \
  710. auto& a = _CAST(_T&, lhs); \
  711. auto& b = _CAST(_T&, rhs); \
  712. for(int i=0; i<a.size() && i<b.size(); i++){ \
  713. if(vm->py_eq(a[i], b[i])) continue; \
  714. return VAR(vm->py_##name(a[i], b[i])); \
  715. } \
  716. return VAR(a.size() op b.size()); \
  717. });
  718. BIND_RICH_CMP(lt, <, tp_list, List)
  719. BIND_RICH_CMP(le, <=, tp_list, List)
  720. BIND_RICH_CMP(gt, >, tp_list, List)
  721. BIND_RICH_CMP(ge, >=, tp_list, List)
  722. BIND_RICH_CMP(lt, <, tp_tuple, Tuple)
  723. BIND_RICH_CMP(le, <=, tp_tuple, Tuple)
  724. BIND_RICH_CMP(gt, >, tp_tuple, Tuple)
  725. BIND_RICH_CMP(ge, >=, tp_tuple, Tuple)
  726. #undef BIND_RICH_CMP
  727. _vm->bind__add__(_vm->tp_list, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  728. const List& self = _CAST(List&, lhs);
  729. const List& other = CAST(List&, rhs);
  730. List new_list(self); // copy construct
  731. new_list.extend(other);
  732. return VAR(std::move(new_list));
  733. });
  734. _vm->bind__len__(_vm->tp_list, [](VM* vm, PyObject* obj) {
  735. return (i64)_CAST(List&, obj).size();
  736. });
  737. _vm->bind__iter__(_vm->tp_list, [](VM* vm, PyObject* obj) {
  738. List& self = _CAST(List&, obj);
  739. return VAR_T(ArrayIter, obj, self.begin(), self.end());
  740. });
  741. _vm->bind__getitem__(_vm->tp_list, PyArrayGetItem<List>);
  742. _vm->bind__setitem__(_vm->tp_list, [](VM* vm, PyObject* obj, PyObject* index, PyObject* value){
  743. List& self = _CAST(List&, obj);
  744. int i = CAST(int, index);
  745. i = vm->normalized_index(i, self.size());
  746. self[i] = value;
  747. });
  748. _vm->bind__delitem__(_vm->tp_list, [](VM* vm, PyObject* obj, PyObject* index){
  749. List& self = _CAST(List&, obj);
  750. int i = CAST(int, index);
  751. i = vm->normalized_index(i, self.size());
  752. self.erase(i);
  753. });
  754. /************ tuple ************/
  755. _vm->bind_constructor<-1>("tuple", [](VM* vm, ArgsView args) {
  756. if(args.size() == 1+0) return VAR(Tuple(0));
  757. if(args.size() == 1+1){
  758. List list = CAST(List, vm->py_list(args[1]));
  759. return VAR(Tuple(std::move(list)));
  760. }
  761. vm->TypeError("tuple() takes at most 1 argument");
  762. return vm->None;
  763. });
  764. _vm->bind__contains__(_vm->tp_tuple, [](VM* vm, PyObject* obj, PyObject* item) {
  765. Tuple& self = _CAST(Tuple&, obj);
  766. for(PyObject* i: self) if(vm->py_eq(i, item)) return vm->True;
  767. return vm->False;
  768. });
  769. _vm->bind_method<1>("tuple", "count", [](VM* vm, ArgsView args) {
  770. Tuple& self = _CAST(Tuple&, args[0]);
  771. int count = 0;
  772. for(PyObject* i: self) if(vm->py_eq(i, args[1])) count++;
  773. return VAR(count);
  774. });
  775. _vm->bind__eq__(_vm->tp_tuple, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  776. const Tuple& self = _CAST(Tuple&, lhs);
  777. if(!is_non_tagged_type(rhs, vm->tp_tuple)) return vm->NotImplemented;
  778. const Tuple& other = _CAST(Tuple&, rhs);
  779. if(self.size() != other.size()) return vm->False;
  780. for(int i = 0; i < self.size(); i++) {
  781. if(!vm->py_eq(self[i], other[i])) return vm->False;
  782. }
  783. return vm->True;
  784. });
  785. _vm->bind__hash__(_vm->tp_tuple, [](VM* vm, PyObject* obj) {
  786. i64 x = 1000003;
  787. const Tuple& items = CAST(Tuple&, obj);
  788. for (int i=0; i<items.size(); i++) {
  789. i64 y = vm->py_hash(items[i]);
  790. // recommended by Github Copilot
  791. x = x ^ (y + 0x9e3779b9 + (x << 6) + (x >> 2));
  792. }
  793. return x;
  794. });
  795. _vm->bind__iter__(_vm->tp_tuple, [](VM* vm, PyObject* obj) {
  796. Tuple& self = _CAST(Tuple&, obj);
  797. return VAR_T(ArrayIter, obj, self.begin(), self.end());
  798. });
  799. _vm->bind__getitem__(_vm->tp_tuple, PyArrayGetItem<Tuple>);
  800. _vm->bind__len__(_vm->tp_tuple, [](VM* vm, PyObject* obj) {
  801. return (i64)_CAST(Tuple&, obj).size();
  802. });
  803. /************ bool ************/
  804. _vm->bind_constructor<2>("bool", PK_LAMBDA(VAR(vm->py_bool(args[1]))));
  805. _vm->bind__hash__(_vm->tp_bool, [](VM* vm, PyObject* obj) {
  806. return (i64)_CAST(bool, obj);
  807. });
  808. _vm->bind__repr__(_vm->tp_bool, [](VM* vm, PyObject* self) {
  809. bool val = _CAST(bool, self);
  810. return VAR(val ? "True" : "False");
  811. });
  812. _vm->bind__and__(_vm->tp_bool, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  813. return VAR(_CAST(bool, lhs) && CAST(bool, rhs));
  814. });
  815. _vm->bind__or__(_vm->tp_bool, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  816. return VAR(_CAST(bool, lhs) || CAST(bool, rhs));
  817. });
  818. _vm->bind__xor__(_vm->tp_bool, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  819. return VAR(_CAST(bool, lhs) != CAST(bool, rhs));
  820. });
  821. _vm->bind__eq__(_vm->tp_bool, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  822. if(is_non_tagged_type(rhs, vm->tp_bool)) return VAR(lhs == rhs);
  823. if(is_int(rhs)) return VAR(_CAST(bool, lhs) == (bool)CAST(i64, rhs));
  824. return vm->NotImplemented;
  825. });
  826. _vm->bind__repr__(_vm->_type("ellipsis"), [](VM* vm, PyObject* self) {
  827. return VAR("...");
  828. });
  829. _vm->bind__repr__(_vm->_type("NotImplementedType"), [](VM* vm, PyObject* self) {
  830. return VAR("NotImplemented");
  831. });
  832. /************ bytes ************/
  833. _vm->bind_constructor<2>("bytes", [](VM* vm, ArgsView args){
  834. List& list = CAST(List&, args[1]);
  835. std::vector<unsigned char> buffer(list.size());
  836. for(int i=0; i<list.size(); i++){
  837. i64 b = CAST(i64, list[i]);
  838. if(b<0 || b>255) vm->ValueError("byte must be in range[0, 256)");
  839. buffer[i] = (char)b;
  840. }
  841. return VAR(Bytes(buffer));
  842. });
  843. _vm->bind__getitem__(_vm->tp_bytes, [](VM* vm, PyObject* obj, PyObject* index) {
  844. const Bytes& self = _CAST(Bytes&, obj);
  845. int i = CAST(int, index);
  846. i = vm->normalized_index(i, self.size());
  847. return VAR(self[i]);
  848. });
  849. _vm->bind__hash__(_vm->tp_bytes, [](VM* vm, PyObject* obj) {
  850. const Bytes& self = _CAST(Bytes&, obj);
  851. std::string_view view((char*)self.data(), self.size());
  852. return (i64)std::hash<std::string_view>()(view);
  853. });
  854. _vm->bind__repr__(_vm->tp_bytes, [](VM* vm, PyObject* obj) {
  855. const Bytes& self = _CAST(Bytes&, obj);
  856. SStream ss;
  857. ss << "b'";
  858. for(int i=0; i<self.size(); i++){
  859. ss << "\\x"; // << std::hex << std::setw(2) << std::setfill('0') << self[i];
  860. ss << "0123456789ABCDEF"[self[i] >> 4];
  861. ss << "0123456789ABCDEF"[self[i] & 0xf];
  862. }
  863. ss << "'";
  864. return VAR(ss.str());
  865. });
  866. _vm->bind__len__(_vm->tp_bytes, [](VM* vm, PyObject* obj) {
  867. return (i64)_CAST(Bytes&, obj).size();
  868. });
  869. _vm->bind_method<0>("bytes", "decode", [](VM* vm, ArgsView args) {
  870. const Bytes& self = _CAST(Bytes&, args[0]);
  871. // TODO: check encoding is utf-8
  872. return VAR(Str(self.str()));
  873. });
  874. _vm->bind__eq__(_vm->tp_bytes, [](VM* vm, PyObject* lhs, PyObject* rhs) {
  875. if(!is_non_tagged_type(rhs, vm->tp_bytes)) return vm->NotImplemented;
  876. return VAR(_CAST(Bytes&, lhs) == _CAST(Bytes&, rhs));
  877. });
  878. /************ slice ************/
  879. _vm->bind_constructor<4>("slice", [](VM* vm, ArgsView args) {
  880. return VAR(Slice(args[1], args[2], args[3]));
  881. });
  882. _vm->bind__repr__(_vm->tp_slice, [](VM* vm, PyObject* obj) {
  883. const Slice& self = _CAST(Slice&, obj);
  884. SStream ss;
  885. ss << "slice(";
  886. ss << CAST(Str, vm->py_repr(self.start)) << ", ";
  887. ss << CAST(Str, vm->py_repr(self.stop)) << ", ";
  888. ss << CAST(Str, vm->py_repr(self.step)) << ")";
  889. return VAR(ss.str());
  890. });
  891. /************ mappingproxy ************/
  892. _vm->bind_method<0>("mappingproxy", "keys", [](VM* vm, ArgsView args) {
  893. MappingProxy& self = _CAST(MappingProxy&, args[0]);
  894. List keys;
  895. for(StrName name : self.attr().keys()) keys.push_back(VAR(name.sv()));
  896. return VAR(std::move(keys));
  897. });
  898. _vm->bind_method<0>("mappingproxy", "values", [](VM* vm, ArgsView args) {
  899. MappingProxy& self = _CAST(MappingProxy&, args[0]);
  900. List values;
  901. for(auto& item : self.attr().items()) values.push_back(item.second);
  902. return VAR(std::move(values));
  903. });
  904. _vm->bind_method<0>("mappingproxy", "items", [](VM* vm, ArgsView args) {
  905. MappingProxy& self = _CAST(MappingProxy&, args[0]);
  906. List items;
  907. for(auto& item : self.attr().items()){
  908. PyObject* t = VAR(Tuple({VAR(item.first.sv()), item.second}));
  909. items.push_back(std::move(t));
  910. }
  911. return VAR(std::move(items));
  912. });
  913. _vm->bind__len__(_vm->tp_mappingproxy, [](VM* vm, PyObject* obj) {
  914. return (i64)_CAST(MappingProxy&, obj).attr().size();
  915. });
  916. _vm->bind__eq__(_vm->tp_mappingproxy, [](VM* vm, PyObject* obj, PyObject* other){
  917. MappingProxy& a = _CAST(MappingProxy&, obj);
  918. if(!is_non_tagged_type(other, vm->tp_mappingproxy)){
  919. return vm->NotImplemented;
  920. }
  921. MappingProxy& b = _CAST(MappingProxy&, other);
  922. return VAR(a.obj == b.obj);
  923. });
  924. _vm->bind__getitem__(_vm->tp_mappingproxy, [](VM* vm, PyObject* obj, PyObject* index) {
  925. MappingProxy& self = _CAST(MappingProxy&, obj);
  926. StrName key = CAST(Str&, index);
  927. PyObject* ret = self.attr().try_get_likely_found(key);
  928. if(ret == nullptr) vm->KeyError(index);
  929. return ret;
  930. });
  931. _vm->bind(_vm->_t(_vm->tp_mappingproxy), "get(self, key, default=None)", [](VM* vm, ArgsView args) {
  932. MappingProxy& self = _CAST(MappingProxy&, args[0]);
  933. StrName key = CAST(Str&, args[1]);
  934. PyObject* ret = self.attr().try_get(key);
  935. if(ret == nullptr) return args[2];
  936. return ret;
  937. });
  938. _vm->bind__repr__(_vm->tp_mappingproxy, [](VM* vm, PyObject* obj) {
  939. MappingProxy& self = _CAST(MappingProxy&, obj);
  940. SStream ss;
  941. ss << "mappingproxy({";
  942. bool first = true;
  943. for(auto& item : self.attr().items()){
  944. if(!first) ss << ", ";
  945. first = false;
  946. ss << item.first.escape() << ": " << CAST(Str, vm->py_repr(item.second));
  947. }
  948. ss << "})";
  949. return VAR(ss.str());
  950. });
  951. _vm->bind__contains__(_vm->tp_mappingproxy, [](VM* vm, PyObject* obj, PyObject* key) {
  952. MappingProxy& self = _CAST(MappingProxy&, obj);
  953. return VAR(self.attr().contains(CAST(Str&, key)));
  954. });
  955. /************ dict ************/
  956. _vm->bind_constructor<-1>("dict", [](VM* vm, ArgsView args){
  957. return VAR(Dict(vm));
  958. });
  959. _vm->bind_method<-1>("dict", "__init__", [](VM* vm, ArgsView args){
  960. if(args.size() == 1+0) return vm->None;
  961. if(args.size() == 1+1){
  962. auto _lock = vm->heap.gc_scope_lock();
  963. Dict& self = _CAST(Dict&, args[0]);
  964. List& list = CAST(List&, args[1]);
  965. for(PyObject* item : list){
  966. Tuple& t = CAST(Tuple&, item);
  967. if(t.size() != 2){
  968. vm->ValueError("dict() takes an iterable of tuples (key, value)");
  969. return vm->None;
  970. }
  971. self.set(t[0], t[1]);
  972. }
  973. return vm->None;
  974. }
  975. vm->TypeError("dict() takes at most 1 argument");
  976. return vm->None;
  977. });
  978. _vm->bind__len__(_vm->tp_dict, [](VM* vm, PyObject* obj) {
  979. return (i64)_CAST(Dict&, obj).size();
  980. });
  981. _vm->bind__getitem__(_vm->tp_dict, [](VM* vm, PyObject* obj, PyObject* index) {
  982. Dict& self = _CAST(Dict&, obj);
  983. PyObject* ret = self.try_get(index);
  984. if(ret == nullptr) vm->KeyError(index);
  985. return ret;
  986. });
  987. _vm->bind__setitem__(_vm->tp_dict, [](VM* vm, PyObject* obj, PyObject* key, PyObject* value) {
  988. Dict& self = _CAST(Dict&, obj);
  989. self.set(key, value);
  990. });
  991. _vm->bind__delitem__(_vm->tp_dict, [](VM* vm, PyObject* obj, PyObject* key) {
  992. Dict& self = _CAST(Dict&, obj);
  993. bool ok = self.erase(key);
  994. if(!ok) vm->KeyError(key);
  995. });
  996. _vm->bind_method<-1>("dict", "pop", [](VM* vm, ArgsView args) {
  997. if(args.size() != 2 && args.size() != 3){
  998. vm->TypeError("pop() expected 1 or 2 arguments");
  999. return vm->None;
  1000. }
  1001. Dict& self = _CAST(Dict&, args[0]);
  1002. PyObject* value = self.try_get(args[1]);
  1003. if(value == nullptr){
  1004. if(args.size() == 2) vm->KeyError(args[1]);
  1005. if(args.size() == 3){
  1006. return args[2];
  1007. }
  1008. }
  1009. self.erase(args[1]);
  1010. return value;
  1011. });
  1012. _vm->bind__contains__(_vm->tp_dict, [](VM* vm, PyObject* obj, PyObject* key) {
  1013. Dict& self = _CAST(Dict&, obj);
  1014. return VAR(self.contains(key));
  1015. });
  1016. _vm->bind__iter__(_vm->tp_dict, [](VM* vm, PyObject* obj) {
  1017. const Dict& self = _CAST(Dict&, obj);
  1018. return vm->py_iter(VAR(self.keys()));
  1019. });
  1020. _vm->bind_method<-1>("dict", "get", [](VM* vm, ArgsView args) {
  1021. Dict& self = _CAST(Dict&, args[0]);
  1022. if(args.size() == 1+1){
  1023. PyObject* ret = self.try_get(args[1]);
  1024. if(ret != nullptr) return ret;
  1025. return vm->None;
  1026. }else if(args.size() == 1+2){
  1027. PyObject* ret = self.try_get(args[1]);
  1028. if(ret != nullptr) return ret;
  1029. return args[2];
  1030. }
  1031. vm->TypeError("get() takes at most 2 arguments");
  1032. return vm->None;
  1033. });
  1034. _vm->bind_method<0>("dict", "keys", [](VM* vm, ArgsView args) {
  1035. const Dict& self = _CAST(Dict&, args[0]);
  1036. return VAR(self.keys());
  1037. });
  1038. _vm->bind_method<0>("dict", "values", [](VM* vm, ArgsView args) {
  1039. const Dict& self = _CAST(Dict&, args[0]);
  1040. return VAR(self.values());
  1041. });
  1042. _vm->bind_method<0>("dict", "items", [](VM* vm, ArgsView args) {
  1043. const Dict& self = _CAST(Dict&, args[0]);
  1044. Tuple items(self.size());
  1045. int j = 0;
  1046. self.apply([&](PyObject* k, PyObject* v){
  1047. items[j++] = VAR(Tuple({k, v}));
  1048. });
  1049. return VAR(std::move(items));
  1050. });
  1051. _vm->bind_method<1>("dict", "update", [](VM* vm, ArgsView args) {
  1052. Dict& self = _CAST(Dict&, args[0]);
  1053. const Dict& other = CAST(Dict&, args[1]);
  1054. self.update(other);
  1055. return vm->None;
  1056. });
  1057. _vm->bind_method<0>("dict", "copy", [](VM* vm, ArgsView args) {
  1058. const Dict& self = _CAST(Dict&, args[0]);
  1059. return VAR(self);
  1060. });
  1061. _vm->bind_method<0>("dict", "clear", [](VM* vm, ArgsView args) {
  1062. Dict& self = _CAST(Dict&, args[0]);
  1063. self.clear();
  1064. return vm->None;
  1065. });
  1066. _vm->bind__repr__(_vm->tp_dict, [](VM* vm, PyObject* obj) {
  1067. Dict& self = _CAST(Dict&, obj);
  1068. SStream ss;
  1069. ss << "{";
  1070. bool first = true;
  1071. self.apply([&](PyObject* k, PyObject* v){
  1072. if(!first) ss << ", ";
  1073. first = false;
  1074. Str key = CAST(Str&, vm->py_repr(k));
  1075. Str value = CAST(Str&, vm->py_repr(v));
  1076. ss << key << ": " << value;
  1077. });
  1078. ss << "}";
  1079. return VAR(ss.str());
  1080. });
  1081. _vm->bind__eq__(_vm->tp_dict, [](VM* vm, PyObject* a, PyObject* b) {
  1082. Dict& self = _CAST(Dict&, a);
  1083. if(!is_non_tagged_type(b, vm->tp_dict)) return vm->NotImplemented;
  1084. Dict& other = _CAST(Dict&, b);
  1085. if(self.size() != other.size()) return vm->False;
  1086. for(int i=0; i<self._capacity; i++){
  1087. auto item = self._items[i];
  1088. if(item.first == nullptr) continue;
  1089. PyObject* value = other.try_get(item.first);
  1090. if(value == nullptr) return vm->False;
  1091. if(!vm->py_eq(item.second, value)) return vm->False;
  1092. }
  1093. return vm->True;
  1094. });
  1095. _vm->bind__repr__(_vm->tp_module, [](VM* vm, PyObject* obj) {
  1096. const Str& path = CAST(Str&, obj->attr(__path__));
  1097. return VAR(fmt("<module ", path.escape(), ">"));
  1098. });
  1099. /************ property ************/
  1100. _vm->bind_constructor<-1>("property", [](VM* vm, ArgsView args) {
  1101. if(args.size() == 1+1){
  1102. return VAR(Property(args[1], vm->None, ""));
  1103. }else if(args.size() == 1+2){
  1104. return VAR(Property(args[1], args[2], ""));
  1105. }else if(args.size() == 1+3){
  1106. return VAR(Property(args[1], args[2], CAST(Str, args[3])));
  1107. }
  1108. vm->TypeError("property() takes at most 3 arguments");
  1109. return vm->None;
  1110. });
  1111. _vm->bind_property(_vm->_t(_vm->tp_property), "__signature__", [](VM* vm, ArgsView args){
  1112. Property& self = _CAST(Property&, args[0]);
  1113. return VAR(self.signature);
  1114. });
  1115. _vm->bind_property(_vm->_t(_vm->tp_function), "__doc__", [](VM* vm, ArgsView args) {
  1116. Function& func = _CAST(Function&, args[0]);
  1117. return VAR(func.decl->docstring);
  1118. });
  1119. _vm->bind_property(_vm->_t(_vm->tp_native_func), "__doc__", [](VM* vm, ArgsView args) {
  1120. NativeFunc& func = _CAST(NativeFunc&, args[0]);
  1121. if(func.decl != nullptr) return VAR(func.decl->docstring);
  1122. return VAR("");
  1123. });
  1124. _vm->bind_property(_vm->_t(_vm->tp_function), "__signature__", [](VM* vm, ArgsView args) {
  1125. Function& func = _CAST(Function&, args[0]);
  1126. return VAR(func.decl->signature);
  1127. });
  1128. // _vm->bind_property(_vm->_t(_vm->tp_function), "__call__", [](VM* vm, ArgsView args) {
  1129. // return args[0];
  1130. // });
  1131. _vm->bind_property(_vm->_t(_vm->tp_native_func), "__signature__", [](VM* vm, ArgsView args) {
  1132. NativeFunc& func = _CAST(NativeFunc&, args[0]);
  1133. if(func.decl != nullptr) return VAR(func.decl->signature);
  1134. return VAR("");
  1135. });
  1136. // _vm->bind_property(_vm->_t(_vm->tp_native_func), "__call__", [](VM* vm, ArgsView args) {
  1137. // return args[0];
  1138. // });
  1139. // Exception
  1140. _vm->bind_constructor<-1>("Exception", [](VM* vm, ArgsView args){
  1141. Type cls = PK_OBJ_GET(Type, args[0]);
  1142. StrName cls_name = obj_type_name(vm, cls);
  1143. PyObject* e_obj = vm->heap.gcnew<Exception>(cls, cls_name);
  1144. e_obj->_enable_instance_dict();
  1145. return e_obj;
  1146. });
  1147. _vm->bind(_vm->_t(_vm->tp_exception), "__init__(self, msg=...)", [](VM* vm, ArgsView args){
  1148. Exception& self = _CAST(Exception&, args[0]);
  1149. if(args[1] == vm->Ellipsis){
  1150. self.msg = "";
  1151. }else{
  1152. self.msg = CAST(Str, args[1]);
  1153. }
  1154. return vm->None;
  1155. });
  1156. _vm->bind__repr__(_vm->tp_exception, [](VM* vm, PyObject* obj) {
  1157. Exception& self = _CAST(Exception&, obj);
  1158. return VAR(fmt(obj_type_name(vm, obj->type), '(', self.msg.escape(), ')'));
  1159. });
  1160. _vm->bind__str__(_vm->tp_exception, [](VM* vm, PyObject* obj) {
  1161. Exception& self = _CAST(Exception&, obj);
  1162. return VAR(self.msg);
  1163. });
  1164. RangeIter::register_class(_vm, _vm->builtins);
  1165. ArrayIter::register_class(_vm, _vm->builtins);
  1166. StringIter::register_class(_vm, _vm->builtins);
  1167. Generator::register_class(_vm, _vm->builtins);
  1168. }
  1169. void add_module_timeit(VM* vm){
  1170. PyObject* mod = vm->new_module("timeit");
  1171. vm->bind_func<2>(mod, "timeit", [](VM* vm, ArgsView args) {
  1172. PyObject* f = args[0];
  1173. i64 iters = CAST(i64, args[1]);
  1174. auto now = std::chrono::system_clock::now();
  1175. for(i64 i=0; i<iters; i++) vm->call(f);
  1176. auto end = std::chrono::system_clock::now();
  1177. f64 elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - now).count() / 1000.0;
  1178. return VAR(elapsed);
  1179. });
  1180. }
  1181. void add_module_operator(VM* vm){
  1182. PyObject* mod = vm->new_module("operator");
  1183. vm->bind_func<2>(mod, "lt", [](VM* vm, ArgsView args) { return VAR(vm->py_lt(args[0], args[1]));});
  1184. vm->bind_func<2>(mod, "le", [](VM* vm, ArgsView args) { return VAR(vm->py_le(args[0], args[1]));});
  1185. vm->bind_func<2>(mod, "eq", [](VM* vm, ArgsView args) { return VAR(vm->py_eq(args[0], args[1]));});
  1186. vm->bind_func<2>(mod, "ne", [](VM* vm, ArgsView args) { return VAR(vm->py_ne(args[0], args[1]));});
  1187. vm->bind_func<2>(mod, "ge", [](VM* vm, ArgsView args) { return VAR(vm->py_ge(args[0], args[1]));});
  1188. vm->bind_func<2>(mod, "gt", [](VM* vm, ArgsView args) { return VAR(vm->py_gt(args[0], args[1]));});
  1189. }
  1190. struct PyStructTime{
  1191. PY_CLASS(PyStructTime, time, struct_time)
  1192. int tm_year;
  1193. int tm_mon;
  1194. int tm_mday;
  1195. int tm_hour;
  1196. int tm_min;
  1197. int tm_sec;
  1198. int tm_wday;
  1199. int tm_yday;
  1200. int tm_isdst;
  1201. PyStructTime(std::time_t t){
  1202. std::tm* tm = std::localtime(&t);
  1203. tm_year = tm->tm_year + 1900;
  1204. tm_mon = tm->tm_mon + 1;
  1205. tm_mday = tm->tm_mday;
  1206. tm_hour = tm->tm_hour;
  1207. tm_min = tm->tm_min;
  1208. tm_sec = tm->tm_sec;
  1209. tm_wday = (tm->tm_wday + 6) % 7;
  1210. tm_yday = tm->tm_yday + 1;
  1211. tm_isdst = tm->tm_isdst;
  1212. }
  1213. PyStructTime* _() { return this; }
  1214. static void _register(VM* vm, PyObject* mod, PyObject* type){
  1215. vm->bind_notimplemented_constructor<PyStructTime>(type);
  1216. PY_READONLY_FIELD(PyStructTime, "tm_year", _, tm_year);
  1217. PY_READONLY_FIELD(PyStructTime, "tm_mon", _, tm_mon);
  1218. PY_READONLY_FIELD(PyStructTime, "tm_mday", _, tm_mday);
  1219. PY_READONLY_FIELD(PyStructTime, "tm_hour", _, tm_hour);
  1220. PY_READONLY_FIELD(PyStructTime, "tm_min", _, tm_min);
  1221. PY_READONLY_FIELD(PyStructTime, "tm_sec", _, tm_sec);
  1222. PY_READONLY_FIELD(PyStructTime, "tm_wday", _, tm_wday);
  1223. PY_READONLY_FIELD(PyStructTime, "tm_yday", _, tm_yday);
  1224. PY_READONLY_FIELD(PyStructTime, "tm_isdst", _, tm_isdst);
  1225. }
  1226. };
  1227. void add_module_time(VM* vm){
  1228. PyObject* mod = vm->new_module("time");
  1229. PyStructTime::register_class(vm, mod);
  1230. vm->bind_func<0>(mod, "time", [](VM* vm, ArgsView args) {
  1231. auto now = std::chrono::system_clock::now();
  1232. return VAR(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count() / 1000.0);
  1233. });
  1234. vm->bind_func<1>(mod, "sleep", [](VM* vm, ArgsView args) {
  1235. f64 seconds = CAST_F(args[0]);
  1236. auto begin = std::chrono::system_clock::now();
  1237. while(true){
  1238. auto now = std::chrono::system_clock::now();
  1239. f64 elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - begin).count() / 1000.0;
  1240. if(elapsed >= seconds) break;
  1241. }
  1242. return vm->None;
  1243. });
  1244. vm->bind_func<0>(mod, "localtime", [](VM* vm, ArgsView args) {
  1245. auto now = std::chrono::system_clock::now();
  1246. std::time_t t = std::chrono::system_clock::to_time_t(now);
  1247. return VAR_T(PyStructTime, t);
  1248. });
  1249. }
  1250. void add_module_sys(VM* vm){
  1251. PyObject* mod = vm->new_module("sys");
  1252. vm->setattr(mod, "version", VAR(PK_VERSION));
  1253. vm->setattr(mod, "platform", VAR(kPlatformStrings[PK_SYS_PLATFORM]));
  1254. PyObject* stdout_ = vm->heap.gcnew<DummyInstance>(vm->tp_object);
  1255. PyObject* stderr_ = vm->heap.gcnew<DummyInstance>(vm->tp_object);
  1256. vm->setattr(mod, "stdout", stdout_);
  1257. vm->setattr(mod, "stderr", stderr_);
  1258. vm->bind_func<1>(stdout_, "write", [](VM* vm, ArgsView args) {
  1259. Str& s = CAST(Str&, args[0]);
  1260. vm->stdout_write(s);
  1261. return vm->None;
  1262. });
  1263. vm->bind_func<1>(stderr_, "write", [](VM* vm, ArgsView args) {
  1264. Str& s = CAST(Str&, args[0]);
  1265. vm->_stderr(s.data, s.size);
  1266. return vm->None;
  1267. });
  1268. }
  1269. void add_module_json(VM* vm){
  1270. PyObject* mod = vm->new_module("json");
  1271. vm->bind_func<1>(mod, "loads", [](VM* vm, ArgsView args) {
  1272. std::string_view sv;
  1273. if(is_non_tagged_type(args[0], vm->tp_bytes)){
  1274. sv = PK_OBJ_GET(Bytes, args[0]).sv();
  1275. }else{
  1276. sv = CAST(Str&, args[0]).sv();
  1277. }
  1278. CodeObject_ code = vm->compile(sv, "<json>", JSON_MODE);
  1279. return vm->_exec(code, vm->top_frame()->_module);
  1280. });
  1281. vm->bind_func<1>(mod, "dumps", [](VM* vm, ArgsView args) {
  1282. return vm->py_json(args[0]);
  1283. });
  1284. }
  1285. // https://docs.python.org/3.5/library/math.html
  1286. void add_module_math(VM* vm){
  1287. PyObject* mod = vm->new_module("math");
  1288. mod->attr().set("pi", VAR(3.1415926535897932384));
  1289. mod->attr().set("e" , VAR(2.7182818284590452354));
  1290. mod->attr().set("inf", VAR(std::numeric_limits<double>::infinity()));
  1291. mod->attr().set("nan", VAR(std::numeric_limits<double>::quiet_NaN()));
  1292. vm->bind_func<1>(mod, "ceil", PK_LAMBDA(VAR((i64)std::ceil(CAST_F(args[0])))));
  1293. vm->bind_func<1>(mod, "fabs", PK_LAMBDA(VAR(std::fabs(CAST_F(args[0])))));
  1294. vm->bind_func<1>(mod, "floor", PK_LAMBDA(VAR((i64)std::floor(CAST_F(args[0])))));
  1295. vm->bind_func<1>(mod, "fsum", [](VM* vm, ArgsView args) {
  1296. List& list = CAST(List&, args[0]);
  1297. double sum = 0;
  1298. double c = 0;
  1299. for(PyObject* arg : list){
  1300. double x = CAST_F(arg);
  1301. double y = x - c;
  1302. double t = sum + y;
  1303. c = (t - sum) - y;
  1304. sum = t;
  1305. }
  1306. return VAR(sum);
  1307. });
  1308. vm->bind_func<2>(mod, "gcd", [](VM* vm, ArgsView args) {
  1309. i64 a = CAST(i64, args[0]);
  1310. i64 b = CAST(i64, args[1]);
  1311. if(a < 0) a = -a;
  1312. if(b < 0) b = -b;
  1313. while(b != 0){
  1314. i64 t = b;
  1315. b = a % b;
  1316. a = t;
  1317. }
  1318. return VAR(a);
  1319. });
  1320. vm->bind_func<1>(mod, "isfinite", PK_LAMBDA(VAR(std::isfinite(CAST_F(args[0])))));
  1321. vm->bind_func<1>(mod, "isinf", PK_LAMBDA(VAR(std::isinf(CAST_F(args[0])))));
  1322. vm->bind_func<1>(mod, "isnan", PK_LAMBDA(VAR(std::isnan(CAST_F(args[0])))));
  1323. vm->bind_func<2>(mod, "isclose", [](VM* vm, ArgsView args) {
  1324. f64 a = CAST_F(args[0]);
  1325. f64 b = CAST_F(args[1]);
  1326. return VAR(std::fabs(a - b) <= Number::kEpsilon);
  1327. });
  1328. vm->bind_func<1>(mod, "exp", PK_LAMBDA(VAR(std::exp(CAST_F(args[0])))));
  1329. vm->bind_func<1>(mod, "log", PK_LAMBDA(VAR(std::log(CAST_F(args[0])))));
  1330. vm->bind_func<1>(mod, "log2", PK_LAMBDA(VAR(std::log2(CAST_F(args[0])))));
  1331. vm->bind_func<1>(mod, "log10", PK_LAMBDA(VAR(std::log10(CAST_F(args[0])))));
  1332. vm->bind_func<2>(mod, "pow", PK_LAMBDA(VAR(std::pow(CAST_F(args[0]), CAST_F(args[1])))));
  1333. vm->bind_func<1>(mod, "sqrt", PK_LAMBDA(VAR(std::sqrt(CAST_F(args[0])))));
  1334. vm->bind_func<1>(mod, "acos", PK_LAMBDA(VAR(std::acos(CAST_F(args[0])))));
  1335. vm->bind_func<1>(mod, "asin", PK_LAMBDA(VAR(std::asin(CAST_F(args[0])))));
  1336. vm->bind_func<1>(mod, "atan", PK_LAMBDA(VAR(std::atan(CAST_F(args[0])))));
  1337. vm->bind_func<2>(mod, "atan2", PK_LAMBDA(VAR(std::atan2(CAST_F(args[0]), CAST_F(args[1])))));
  1338. vm->bind_func<1>(mod, "cos", PK_LAMBDA(VAR(std::cos(CAST_F(args[0])))));
  1339. vm->bind_func<1>(mod, "sin", PK_LAMBDA(VAR(std::sin(CAST_F(args[0])))));
  1340. vm->bind_func<1>(mod, "tan", PK_LAMBDA(VAR(std::tan(CAST_F(args[0])))));
  1341. vm->bind_func<1>(mod, "degrees", PK_LAMBDA(VAR(CAST_F(args[0]) * 180 / 3.1415926535897932384)));
  1342. vm->bind_func<1>(mod, "radians", PK_LAMBDA(VAR(CAST_F(args[0]) * 3.1415926535897932384 / 180)));
  1343. vm->bind_func<1>(mod, "modf", [](VM* vm, ArgsView args) {
  1344. f64 i;
  1345. f64 f = std::modf(CAST_F(args[0]), &i);
  1346. return VAR(Tuple({VAR(f), VAR(i)}));
  1347. });
  1348. vm->bind_func<1>(mod, "factorial", [](VM* vm, ArgsView args) {
  1349. i64 n = CAST(i64, args[0]);
  1350. if(n < 0) vm->ValueError("factorial() not defined for negative values");
  1351. i64 r = 1;
  1352. for(i64 i=2; i<=n; i++) r *= i;
  1353. return VAR(r);
  1354. });
  1355. }
  1356. void add_module_traceback(VM* vm){
  1357. PyObject* mod = vm->new_module("traceback");
  1358. vm->bind_func<0>(mod, "print_exc", [](VM* vm, ArgsView args) {
  1359. if(vm->_last_exception==nullptr) vm->ValueError("no exception");
  1360. Exception& e = _CAST(Exception&, vm->_last_exception);
  1361. vm->stdout_write(e.summary());
  1362. return vm->None;
  1363. });
  1364. vm->bind_func<0>(mod, "format_exc", [](VM* vm, ArgsView args) {
  1365. if(vm->_last_exception==nullptr) vm->ValueError("no exception");
  1366. Exception& e = _CAST(Exception&, vm->_last_exception);
  1367. return VAR(e.summary());
  1368. });
  1369. }
  1370. void add_module_dis(VM* vm){
  1371. PyObject* mod = vm->new_module("dis");
  1372. static const auto get_code = [](VM* vm, PyObject* obj)->CodeObject_{
  1373. if(is_type(obj, vm->tp_str)){
  1374. const Str& source = CAST(Str, obj);
  1375. return vm->compile(source, "<dis>", EXEC_MODE);
  1376. }
  1377. PyObject* f = obj;
  1378. if(is_type(f, vm->tp_bound_method)) f = CAST(BoundMethod, obj).func;
  1379. return CAST(Function&, f).decl->code;
  1380. };
  1381. vm->bind_func<1>(mod, "dis", [](VM* vm, ArgsView args) {
  1382. CodeObject_ code = get_code(vm, args[0]);
  1383. vm->stdout_write(vm->disassemble(code));
  1384. return vm->None;
  1385. });
  1386. }
  1387. void add_module_gc(VM* vm){
  1388. PyObject* mod = vm->new_module("gc");
  1389. vm->bind_func<0>(mod, "collect", PK_LAMBDA(VAR(vm->heap.collect())));
  1390. }
  1391. void VM::post_init(){
  1392. init_builtins(this);
  1393. bind_method<-1>("module", "__init__", [](VM* vm, ArgsView args) {
  1394. vm->NotImplementedError();
  1395. return vm->None;
  1396. });
  1397. bind_method<1>("property", "setter", [](VM* vm, ArgsView args) {
  1398. Property& self = _CAST(Property&, args[0]);
  1399. // The setter's name is not necessary to be the same as the property's name
  1400. // However, for cpython compatibility, we recommend to use the same name
  1401. self.setter = args[1];
  1402. return args[0];
  1403. });
  1404. // type
  1405. bind__getitem__(tp_type, [](VM* vm, PyObject* self, PyObject* _){
  1406. PK_UNUSED(_);
  1407. return self; // for generics
  1408. });
  1409. bind_property(_t(tp_type), "__annotations__", [](VM* vm, ArgsView args){
  1410. PyTypeInfo* ti = vm->_type_info(PK_OBJ_GET(Type, args[0]));
  1411. Tuple t(ti->annotated_fields.size());
  1412. for(int i=0; i<ti->annotated_fields.size(); i++){
  1413. t[i] = VAR(ti->annotated_fields[i].sv());
  1414. }
  1415. return VAR(std::move(t));
  1416. });
  1417. bind__repr__(tp_type, [](VM* vm, PyObject* self){
  1418. SStream ss;
  1419. const PyTypeInfo& info = vm->_all_types[PK_OBJ_GET(Type, self)];
  1420. ss << "<class '" << info.name << "'>";
  1421. return VAR(ss.str());
  1422. });
  1423. bind_property(_t(tp_object), "__class__", PK_LAMBDA(vm->_t(args[0])));
  1424. bind_property(_t(tp_type), "__base__", [](VM* vm, ArgsView args){
  1425. const PyTypeInfo& info = vm->_all_types[PK_OBJ_GET(Type, args[0])];
  1426. return info.base.index == -1 ? vm->None : vm->_all_types[info.base].obj;
  1427. });
  1428. bind_property(_t(tp_type), "__name__", [](VM* vm, ArgsView args){
  1429. const PyTypeInfo& info = vm->_all_types[PK_OBJ_GET(Type, args[0])];
  1430. return VAR(info.name.sv());
  1431. });
  1432. bind_property(_t(tp_type), "__module__", [](VM* vm, ArgsView args){
  1433. const PyTypeInfo& info = vm->_all_types[PK_OBJ_GET(Type, args[0])];
  1434. if(info.mod == nullptr) return vm->None;
  1435. return info.mod;
  1436. });
  1437. bind_property(_t(tp_bound_method), "__self__", [](VM* vm, ArgsView args){
  1438. return CAST(BoundMethod&, args[0]).self;
  1439. });
  1440. bind_property(_t(tp_bound_method), "__func__", [](VM* vm, ArgsView args){
  1441. return CAST(BoundMethod&, args[0]).func;
  1442. });
  1443. bind__eq__(tp_bound_method, [](VM* vm, PyObject* lhs, PyObject* rhs){
  1444. if(!is_non_tagged_type(rhs, vm->tp_bound_method)) return vm->NotImplemented;
  1445. return VAR(_CAST(BoundMethod&, lhs) == _CAST(BoundMethod&, rhs));
  1446. });
  1447. bind_property(_t(tp_slice), "start", [](VM* vm, ArgsView args){
  1448. return CAST(Slice&, args[0]).start;
  1449. });
  1450. bind_property(_t(tp_slice), "stop", [](VM* vm, ArgsView args){
  1451. return CAST(Slice&, args[0]).stop;
  1452. });
  1453. bind_property(_t(tp_slice), "step", [](VM* vm, ArgsView args){
  1454. return CAST(Slice&, args[0]).step;
  1455. });
  1456. bind_property(_t(tp_object), "__dict__", [](VM* vm, ArgsView args){
  1457. if(is_tagged(args[0]) || !args[0]->is_attr_valid()) return vm->None;
  1458. return VAR(MappingProxy(args[0]));
  1459. });
  1460. #if !PK_DEBUG_NO_BUILTINS
  1461. add_module_sys(this);
  1462. add_module_traceback(this);
  1463. add_module_time(this);
  1464. add_module_json(this);
  1465. add_module_math(this);
  1466. add_module_re(this);
  1467. add_module_dis(this);
  1468. add_module_c(this);
  1469. add_module_gc(this);
  1470. add_module_random(this);
  1471. add_module_base64(this);
  1472. add_module_timeit(this);
  1473. add_module_operator(this);
  1474. add_module_csv(this);
  1475. for(const char* name: {"this", "functools", "heapq", "bisect", "pickle", "_long", "colorsys", "typing", "datetime", "dataclasses", "cmath"}){
  1476. _lazy_modules[name] = kPythonLibs[name];
  1477. }
  1478. try{
  1479. CodeObject_ code = compile(kPythonLibs["builtins"], "<builtins>", EXEC_MODE);
  1480. this->_exec(code, this->builtins);
  1481. code = compile(kPythonLibs["_set"], "<set>", EXEC_MODE);
  1482. this->_exec(code, this->builtins);
  1483. }catch(const Exception& e){
  1484. std::cerr << e.summary() << std::endl;
  1485. std::cerr << "failed to load builtins module!!" << std::endl;
  1486. exit(1);
  1487. }
  1488. if(enable_os){
  1489. add_module_io(this);
  1490. add_module_os(this);
  1491. _import_handler = _default_import_handler;
  1492. }
  1493. add_module_linalg(this);
  1494. add_module_easing(this);
  1495. add_module_collections(this);
  1496. #ifdef PK_USE_BOX2D
  1497. add_module_box2d(this);
  1498. #endif
  1499. #ifdef PK_USE_CJSON
  1500. add_module_cjson(this);
  1501. #endif
  1502. #endif
  1503. }
  1504. CodeObject_ VM::compile(Str source, Str filename, CompileMode mode, bool unknown_global_scope) {
  1505. Compiler compiler(this, std::move(source), filename, mode, unknown_global_scope);
  1506. try{
  1507. return compiler.compile();
  1508. }catch(const Exception& e){
  1509. #if PK_DEBUG_FULL_EXCEPTION
  1510. std::cerr << e.summary() << std::endl;
  1511. #endif
  1512. _error(e._self);
  1513. return nullptr;
  1514. }
  1515. }
  1516. } // namespace pkpy