pocketpy.cpp 62 KB

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