pocketpy.cpp 62 KB

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