pocketpy.cpp 58 KB

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