pocketpy.cpp 57 KB

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