modules.cpp 12 KB

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