modules.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. #include "pocketpy/modules/modules.hpp"
  2. #include "pocketpy/interpreter/bindings.hpp"
  3. #include "pocketpy/common/export.h"
  4. #include "pocketpy/common/_generated.h"
  5. #include <chrono>
  6. #include <cmath>
  7. namespace pkpy {
  8. struct PyStructTime {
  9. int tm_year;
  10. int tm_mon;
  11. int tm_mday;
  12. int tm_hour;
  13. int tm_min;
  14. int tm_sec;
  15. int tm_wday;
  16. int tm_yday;
  17. int tm_isdst;
  18. PyStructTime(std::time_t t) {
  19. std::tm* tm = std::localtime(&t);
  20. tm_year = tm->tm_year + 1900;
  21. tm_mon = tm->tm_mon + 1;
  22. tm_mday = tm->tm_mday;
  23. tm_hour = tm->tm_hour;
  24. tm_min = tm->tm_min;
  25. tm_sec = tm->tm_sec;
  26. tm_wday = (tm->tm_wday + 6) % 7;
  27. tm_yday = tm->tm_yday + 1;
  28. tm_isdst = tm->tm_isdst;
  29. }
  30. static void _register(VM* vm, PyObject* mod, PyObject* type) {
  31. PY_READONLY_FIELD(PyStructTime, "tm_year", tm_year);
  32. PY_READONLY_FIELD(PyStructTime, "tm_mon", tm_mon);
  33. PY_READONLY_FIELD(PyStructTime, "tm_mday", tm_mday);
  34. PY_READONLY_FIELD(PyStructTime, "tm_hour", tm_hour);
  35. PY_READONLY_FIELD(PyStructTime, "tm_min", tm_min);
  36. PY_READONLY_FIELD(PyStructTime, "tm_sec", tm_sec);
  37. PY_READONLY_FIELD(PyStructTime, "tm_wday", tm_wday);
  38. PY_READONLY_FIELD(PyStructTime, "tm_yday", tm_yday);
  39. PY_READONLY_FIELD(PyStructTime, "tm_isdst", tm_isdst);
  40. }
  41. };
  42. void add_module_time(VM* vm) {
  43. PyObject* mod = vm->new_module("time");
  44. vm->register_user_class<PyStructTime>(mod, "struct_time");
  45. vm->bind_func(mod, "time", 0, [](VM* vm, ArgsView args) {
  46. auto now = std::chrono::system_clock::now();
  47. return VAR(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count() / 1000.0);
  48. });
  49. vm->bind_func(mod, "sleep", 1, [](VM* vm, ArgsView args) {
  50. f64 seconds = CAST_F(args[0]);
  51. auto begin = std::chrono::system_clock::now();
  52. while(true) {
  53. auto now = std::chrono::system_clock::now();
  54. f64 elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - begin).count() / 1000.0;
  55. if(elapsed >= seconds) break;
  56. }
  57. return vm->None;
  58. });
  59. vm->bind_func(mod, "localtime", 0, [](VM* vm, ArgsView args) {
  60. auto now = std::chrono::system_clock::now();
  61. std::time_t t = std::chrono::system_clock::to_time_t(now);
  62. return vm->new_user_object<PyStructTime>(t);
  63. });
  64. }
  65. void add_module_sys(VM* vm) {
  66. PyObject* mod = vm->new_module("sys");
  67. vm->setattr(mod, "version", VAR(PK_VERSION));
  68. vm->setattr(mod, "platform", VAR(kPlatformStrings[PK_SYS_PLATFORM]));
  69. PyObject* stdout_ = vm->new_object<DummyInstance>(vm->tp_object).get();
  70. PyObject* stderr_ = vm->new_object<DummyInstance>(vm->tp_object).get();
  71. vm->setattr(mod, "stdout", stdout_);
  72. vm->setattr(mod, "stderr", stderr_);
  73. vm->bind_func(stdout_, "write", 1, [](VM* vm, ArgsView args) {
  74. Str& s = CAST(Str&, args[0]);
  75. vm->stdout_write(s);
  76. return vm->None;
  77. });
  78. vm->bind_func(stderr_, "write", 1, [](VM* vm, ArgsView args) {
  79. Str& s = CAST(Str&, args[0]);
  80. vm->stderr_write(s);
  81. return vm->None;
  82. });
  83. }
  84. void add_module_json(VM* vm) {
  85. PyObject* mod = vm->new_module("json");
  86. vm->bind_func(mod, "loads", 1, [](VM* vm, ArgsView args) {
  87. std::string_view sv;
  88. if(is_type(args[0], vm->tp_bytes)) {
  89. const Bytes& b = PK_OBJ_GET(Bytes, args[0]);
  90. sv = std::string_view((char*)b.data(), b.size());
  91. } else {
  92. sv = CAST(Str&, args[0]).sv();
  93. }
  94. CodeObject* code = vm->compile(sv, "<json>", JSON_MODE);
  95. PyVar retval = vm->_exec(code, vm->callstack.top()._module);
  96. CodeObject__delete(code);
  97. return retval;
  98. });
  99. vm->bind_func(mod, "dumps", 1, [](VM* vm, ArgsView args) {
  100. return VAR(vm->py_json(args[0]));
  101. });
  102. }
  103. // https://docs.python.org/3.5/library/math.html
  104. void add_module_math(VM* vm) {
  105. PyObject* mod = vm->new_module("math");
  106. mod->attr().set("pi", VAR(3.1415926535897932384));
  107. mod->attr().set("e", VAR(2.7182818284590452354));
  108. mod->attr().set("inf", VAR(std::numeric_limits<double>::infinity()));
  109. mod->attr().set("nan", VAR(std::numeric_limits<double>::quiet_NaN()));
  110. vm->bind_func(mod, "ceil", 1, PK_LAMBDA(VAR((i64)std::ceil(CAST_F(args[0])))));
  111. vm->bind_func(mod, "fabs", 1, PK_LAMBDA(VAR(std::fabs(CAST_F(args[0])))));
  112. vm->bind_func(mod, "floor", 1, PK_LAMBDA(VAR((i64)std::floor(CAST_F(args[0])))));
  113. vm->bind_func(mod, "fsum", 1, [](VM* vm, ArgsView args) {
  114. List& list = CAST(List&, args[0]);
  115. double sum = 0;
  116. double c = 0;
  117. for(PyVar arg: list) {
  118. double x = CAST_F(arg);
  119. double y = x - c;
  120. double t = sum + y;
  121. c = (t - sum) - y;
  122. sum = t;
  123. }
  124. return VAR(sum);
  125. });
  126. vm->bind_func(mod, "gcd", 2, [](VM* vm, ArgsView args) {
  127. i64 a = CAST(i64, args[0]);
  128. i64 b = CAST(i64, args[1]);
  129. if(a < 0) a = -a;
  130. if(b < 0) b = -b;
  131. while(b != 0) {
  132. i64 t = b;
  133. b = a % b;
  134. a = t;
  135. }
  136. return VAR(a);
  137. });
  138. vm->bind_func(mod, "isfinite", 1, PK_LAMBDA(VAR(std::isfinite(CAST_F(args[0])))));
  139. vm->bind_func(mod, "isinf", 1, PK_LAMBDA(VAR(std::isinf(CAST_F(args[0])))));
  140. vm->bind_func(mod, "isnan", 1, PK_LAMBDA(VAR(std::isnan(CAST_F(args[0])))));
  141. vm->bind_func(mod, "isclose", 2, [](VM* vm, ArgsView args) {
  142. f64 a = CAST_F(args[0]);
  143. f64 b = CAST_F(args[1]);
  144. return VAR(std::fabs(a - b) < 1e-9);
  145. });
  146. vm->bind_func(mod, "exp", 1, PK_LAMBDA(VAR(std::exp(CAST_F(args[0])))));
  147. vm->bind(mod, "log(x, base=2.718281828459045)", [](VM* vm, ArgsView args) {
  148. f64 x = CAST_F(args[0]);
  149. f64 base = CAST_F(args[1]);
  150. return VAR(std::log(x) / std::log(base));
  151. });
  152. vm->bind_func(mod, "log2", 1, PK_LAMBDA(VAR(std::log2(CAST_F(args[0])))));
  153. vm->bind_func(mod, "log10", 1, PK_LAMBDA(VAR(std::log10(CAST_F(args[0])))));
  154. vm->bind_func(mod, "pow", 2, PK_LAMBDA(VAR(std::pow(CAST_F(args[0]), CAST_F(args[1])))));
  155. vm->bind_func(mod, "sqrt", 1, PK_LAMBDA(VAR(std::sqrt(CAST_F(args[0])))));
  156. vm->bind_func(mod, "acos", 1, PK_LAMBDA(VAR(std::acos(CAST_F(args[0])))));
  157. vm->bind_func(mod, "asin", 1, PK_LAMBDA(VAR(std::asin(CAST_F(args[0])))));
  158. vm->bind_func(mod, "atan", 1, PK_LAMBDA(VAR(std::atan(CAST_F(args[0])))));
  159. vm->bind_func(mod, "atan2", 2, PK_LAMBDA(VAR(std::atan2(CAST_F(args[0]), CAST_F(args[1])))));
  160. vm->bind_func(mod, "cos", 1, PK_LAMBDA(VAR(std::cos(CAST_F(args[0])))));
  161. vm->bind_func(mod, "sin", 1, PK_LAMBDA(VAR(std::sin(CAST_F(args[0])))));
  162. vm->bind_func(mod, "tan", 1, PK_LAMBDA(VAR(std::tan(CAST_F(args[0])))));
  163. vm->bind_func(mod, "degrees", 1, PK_LAMBDA(VAR(CAST_F(args[0]) * 180 / 3.1415926535897932384)));
  164. vm->bind_func(mod, "radians", 1, PK_LAMBDA(VAR(CAST_F(args[0]) * 3.1415926535897932384 / 180)));
  165. vm->bind_func(mod, "modf", 1, [](VM* vm, ArgsView args) {
  166. f64 i;
  167. f64 f = std::modf(CAST_F(args[0]), &i);
  168. return VAR(Tuple(VAR(f), VAR(i)));
  169. });
  170. vm->bind_func(mod, "factorial", 1, [](VM* vm, ArgsView args) {
  171. i64 n = CAST(i64, args[0]);
  172. if(n < 0) vm->ValueError("factorial() not defined for negative values");
  173. i64 r = 1;
  174. for(i64 i = 2; i <= n; i++)
  175. r *= i;
  176. return VAR(r);
  177. });
  178. }
  179. void add_module_traceback(VM* vm) {
  180. PyObject* mod = vm->new_module("traceback");
  181. vm->bind_func(mod, "print_exc", 0, [](VM* vm, ArgsView args) {
  182. if(vm->__last_exception == nullptr) vm->ValueError("no exception");
  183. Exception& e = vm->__last_exception->as<Exception>();
  184. vm->stdout_write(e.summary());
  185. return vm->None;
  186. });
  187. vm->bind_func(mod, "format_exc", 0, [](VM* vm, ArgsView args) {
  188. if(vm->__last_exception == nullptr) vm->ValueError("no exception");
  189. Exception& e = vm->__last_exception->as<Exception>();
  190. return VAR(e.summary());
  191. });
  192. }
  193. void add_module_dis(VM* vm) {
  194. PyObject* mod = vm->new_module("dis");
  195. vm->bind_func(mod, "dis", 1, [](VM* vm, ArgsView args) {
  196. CodeObject* code;
  197. bool need_delete = false;
  198. PyVar obj = args[0];
  199. if(is_type(obj, vm->tp_str)) {
  200. const Str& source = CAST(Str, obj);
  201. code = vm->compile(source, "<dis>", EXEC_MODE);
  202. need_delete = true;
  203. }
  204. PyVar f = obj;
  205. if(is_type(f, vm->tp_bound_method)) f = CAST(BoundMethod, obj).func;
  206. code = CAST(Function&, f).decl->code;
  207. vm->stdout_write(vm->disassemble(code));
  208. if(need_delete) CodeObject__delete(code);
  209. return vm->None;
  210. });
  211. }
  212. void add_module_gc(VM* vm) {
  213. PyObject* mod = vm->new_module("gc");
  214. vm->bind_func(mod, "collect", 0, PK_LAMBDA(VAR(pk_ManagedHeap__collect(&vm->heap))));
  215. }
  216. void add_module_enum(VM* vm) {
  217. PyObject* mod = vm->new_module("enum");
  218. CodeObject* code = vm->compile(kPythonLibs__enum, "enum.py", EXEC_MODE);
  219. vm->_exec(code, mod);
  220. CodeObject__delete(code);
  221. PyVar Enum = mod->attr("Enum");
  222. vm->_all_types[PK_OBJ_GET(Type, Enum)].on_end_subclass = [](VM* vm, PyTypeInfo* new_ti) {
  223. new_ti->subclass_enabled = false; // Enum class cannot be subclassed twice
  224. NameDict& attr = new_ti->obj->attr();
  225. for(auto [k, v]: attr.items()) {
  226. // wrap every attribute
  227. std::string_view k_sv = k.sv();
  228. if(k_sv.empty() || k_sv[0] == '_') continue;
  229. attr.set(k, vm->call(new_ti->obj, VAR(k_sv), v));
  230. }
  231. };
  232. }
  233. void add_module___builtins(VM* vm) {
  234. PyObject* mod = vm->new_module("__builtins");
  235. vm->bind_func(mod, "next", 1, [](VM* vm, ArgsView args) {
  236. return vm->py_next(args[0]);
  237. });
  238. vm->bind_func(mod, "_enable_instance_dict", 1, [](VM* vm, ArgsView args) {
  239. PyVar self = args[0];
  240. if(is_tagged(self)) vm->TypeError("object: tagged object cannot enable instance dict");
  241. if(self->is_attr_valid()) vm->RuntimeError("object: instance dict is already enabled");
  242. self->_attr = new NameDict();
  243. return vm->None;
  244. });
  245. }
  246. /************************************************/
  247. #if PK_ENABLE_PROFILER
  248. struct LineProfilerW;
  249. struct _LpGuard {
  250. PK_ALWAYS_PASS_BY_POINTER(_LpGuard)
  251. LineProfilerW* lp;
  252. VM* vm;
  253. _LpGuard(LineProfilerW* lp, VM* vm);
  254. ~_LpGuard();
  255. };
  256. // line_profiler wrapper
  257. struct LineProfilerW {
  258. LineProfiler profiler;
  259. static void _register(VM* vm, PyObject* mod, PyObject* type) {
  260. vm->bind_func(type, __new__, 1, [](VM* vm, ArgsView args) {
  261. Type cls = PK_OBJ_GET(Type, args[0]);
  262. return vm->new_object<LineProfilerW>(cls);
  263. });
  264. vm->bind(type, "add_function(self, func)", [](VM* vm, ArgsView args) {
  265. LineProfilerW& self = PK_OBJ_GET(LineProfilerW, args[0]);
  266. vm->check_type(args[1], VM::tp_function);
  267. auto decl = PK_OBJ_GET(Function, args[1]).decl.get();
  268. self.profiler.functions.push_back(decl);
  269. return vm->None;
  270. });
  271. vm->bind(type, "runcall(self, func, *args)", [](VM* vm, ArgsView view) {
  272. LineProfilerW& self = PK_OBJ_GET(LineProfilerW, view[0]);
  273. PyVar func = view[1];
  274. const Tuple& args = CAST(Tuple&, view[2]);
  275. vm->s_data.push(func);
  276. vm->s_data.push(PY_NULL);
  277. for(PyVar arg: args)
  278. vm->s_data.push(arg);
  279. _LpGuard guard(&self, vm);
  280. PyVar ret = vm->vectorcall(args.size());
  281. return ret;
  282. });
  283. vm->bind(type, "print_stats(self)", [](VM* vm, ArgsView args) {
  284. LineProfilerW& self = PK_OBJ_GET(LineProfilerW, args[0]);
  285. vm->stdout_write(self.profiler.stats());
  286. return vm->None;
  287. });
  288. }
  289. };
  290. _LpGuard::_LpGuard(LineProfilerW* lp, VM* vm) : lp(lp), vm(vm) {
  291. if(vm->_profiler) { vm->ValueError("only one profiler can be enabled at a time"); }
  292. vm->_profiler = &lp->profiler;
  293. lp->profiler.begin();
  294. }
  295. _LpGuard::~_LpGuard() {
  296. vm->_profiler = nullptr;
  297. lp->profiler.end();
  298. }
  299. void add_module_line_profiler(VM* vm) {
  300. PyObject* mod = vm->new_module("line_profiler");
  301. vm->register_user_class<LineProfilerW>(mod, "LineProfiler");
  302. }
  303. #else
  304. void add_module_line_profiler(VM* vm) { (void)vm; }
  305. #endif
  306. } // namespace pkpy