pocketpy.cpp 58 KB

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