modules.cpp 12 KB

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