modules.cpp 12 KB

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