modules.cpp 12 KB

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