pocketpy.cpp 64 KB

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