pocketpy.cpp 58 KB

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