modules.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. #include "pocketpy/pocketpy.h"
  2. #include "pocketpy/common/utils.h"
  3. #include "pocketpy/objects/object.h"
  4. #include "pocketpy/common/sstream.h"
  5. #include "pocketpy/interpreter/vm.h"
  6. #include "pocketpy/common/_generated.h"
  7. py_Ref py_getmodule(const char* path) {
  8. VM* vm = pk_current_vm;
  9. return NameDict__try_get(&vm->modules, py_name(path));
  10. }
  11. py_Ref py_newmodule(const char* path) {
  12. ManagedHeap* heap = &pk_current_vm->heap;
  13. PyObject* obj = ManagedHeap__new(heap, tp_module, -1, 0);
  14. py_Ref r0 = py_pushtmp();
  15. py_Ref r1 = py_pushtmp();
  16. *r0 = (py_TValue){
  17. .type = obj->type,
  18. .is_ptr = true,
  19. ._obj = obj,
  20. };
  21. int last_dot = c11_sv__rindex((c11_sv){path, strlen(path)}, '.');
  22. if(last_dot == -1) {
  23. py_newstr(r1, path);
  24. py_setdict(r0, __name__, r1);
  25. py_newstr(r1, "");
  26. py_setdict(r0, __package__, r1);
  27. } else {
  28. const char* start = path + last_dot + 1;
  29. py_newstr(r1, start);
  30. py_setdict(r0, __name__, r1);
  31. py_newstrn(r1, path, last_dot);
  32. py_setdict(r0, __package__, r1);
  33. }
  34. py_newstr(r1, path);
  35. py_setdict(r0, __path__, r1);
  36. // we do not allow override in order to avoid memory leak
  37. // it is because Module objects are not garbage collected
  38. py_Name path_name = py_name(path);
  39. bool exists = NameDict__contains(&pk_current_vm->modules, path_name);
  40. if(exists) c11__abort("module '%s' already exists", path);
  41. NameDict__set(&pk_current_vm->modules, path_name, *r0);
  42. py_shrink(2);
  43. return py_getmodule(path);
  44. }
  45. int py_import(const char* path_cstr) {
  46. // printf("importing %s\n", path_cstr);
  47. VM* vm = pk_current_vm;
  48. c11_sv path = {path_cstr, strlen(path_cstr)};
  49. if(path.size == 0) return ValueError("empty module name");
  50. if(path.data[0] == '.') {
  51. // try relative import
  52. int dot_count = 1;
  53. while(dot_count < path.size && path.data[dot_count] == '.')
  54. dot_count++;
  55. c11_sv top_filename = c11_string__sv(vm->top_frame->co->src->filename);
  56. int is_init = c11_sv__endswith(top_filename, (c11_sv){"__init__.py", 11});
  57. py_Ref package = py_getdict(vm->top_frame->module, __path__);
  58. c11_sv package_sv = py_tosv(package);
  59. if(package_sv.size == 0) {
  60. return ImportError("attempted relative import with no known parent package");
  61. }
  62. c11_vector /* T=c11_sv */ cpnts = c11_sv__split(package_sv, '.');
  63. for(int i = is_init; i < dot_count; i++) {
  64. if(cpnts.count == 0)
  65. return ImportError("attempted relative import beyond top-level package");
  66. c11_vector__pop(&cpnts);
  67. }
  68. if(dot_count < path.size) {
  69. c11_sv last_cpnt = c11_sv__slice(path, dot_count);
  70. c11_vector__push(c11_sv, &cpnts, last_cpnt);
  71. }
  72. // join cpnts
  73. c11_sbuf buf;
  74. c11_sbuf__ctor(&buf);
  75. for(int i = 0; i < cpnts.count; i++) {
  76. if(i > 0) c11_sbuf__write_char(&buf, '.');
  77. c11_sbuf__write_sv(&buf, c11__getitem(c11_sv, &cpnts, i));
  78. }
  79. c11_vector__dtor(&cpnts);
  80. c11_string* new_path = c11_sbuf__submit(&buf);
  81. int res = py_import(new_path->data);
  82. c11_string__delete(new_path);
  83. return res;
  84. }
  85. assert(path.data[0] != '.' && path.data[path.size - 1] != '.');
  86. // check existing module
  87. py_TmpRef ext_mod = py_getmodule(path.data);
  88. if(ext_mod) {
  89. py_assign(py_retval(), ext_mod);
  90. return true;
  91. }
  92. // try import
  93. c11_string* slashed_path = c11_sv__replace(path, '.', PK_PLATFORM_SEP);
  94. c11_string* filename = c11_string__new3("%s.py", slashed_path->data);
  95. bool need_free = true;
  96. const char* data = load_kPythonLib(path_cstr);
  97. if(data != NULL) {
  98. need_free = false;
  99. goto __SUCCESS;
  100. }
  101. data = vm->import_file(filename->data);
  102. if(data != NULL) goto __SUCCESS;
  103. c11_string__delete(filename);
  104. filename = c11_string__new3("%s/__init__.py", slashed_path->data);
  105. data = vm->import_file(filename->data);
  106. if(data != NULL) goto __SUCCESS;
  107. c11_string__delete(filename);
  108. c11_string__delete(slashed_path);
  109. return 0;
  110. __SUCCESS:
  111. py_push(py_newmodule(path_cstr));
  112. py_Ref mod = py_peek(-1);
  113. bool ok = py_exec((const char*)data, filename->data, EXEC_MODE, mod);
  114. py_assign(py_retval(), mod);
  115. py_pop();
  116. c11_string__delete(filename);
  117. c11_string__delete(slashed_path);
  118. if(need_free) free((void*)data);
  119. return ok ? 1 : -1;
  120. }
  121. //////////////////////////
  122. static bool builtins_repr(int argc, py_Ref argv) {
  123. PY_CHECK_ARGC(1);
  124. return py_repr(argv);
  125. }
  126. static bool builtins_exit(int argc, py_Ref argv) {
  127. int code = 0;
  128. if(argc > 1) return TypeError("exit() takes at most 1 argument");
  129. if(argc == 1) {
  130. PY_CHECK_ARG_TYPE(0, tp_int);
  131. code = py_toint(argv);
  132. }
  133. // return py_exception("SystemExit", "%d", code);
  134. exit(code);
  135. return false;
  136. }
  137. static bool builtins_len(int argc, py_Ref argv) {
  138. PY_CHECK_ARGC(1);
  139. return py_len(argv);
  140. }
  141. static bool builtins_hex(int argc, py_Ref argv) {
  142. PY_CHECK_ARGC(1);
  143. PY_CHECK_ARG_TYPE(0, tp_int);
  144. py_i64 val = py_toint(argv);
  145. if(val == 0) {
  146. py_newstr(py_retval(), "0x0");
  147. return true;
  148. }
  149. c11_sbuf ss;
  150. c11_sbuf__ctor(&ss);
  151. if(val < 0) {
  152. c11_sbuf__write_char(&ss, '-');
  153. val = -val;
  154. }
  155. c11_sbuf__write_cstr(&ss, "0x");
  156. bool non_zero = true;
  157. for(int i = 56; i >= 0; i -= 8) {
  158. unsigned char cpnt = (val >> i) & 0xff;
  159. c11_sbuf__write_hex(&ss, cpnt, non_zero);
  160. if(cpnt != 0) non_zero = false;
  161. }
  162. c11_sbuf__py_submit(&ss, py_retval());
  163. return true;
  164. }
  165. static bool builtins_iter(int argc, py_Ref argv) {
  166. PY_CHECK_ARGC(1);
  167. return py_iter(argv);
  168. }
  169. static bool builtins_next(int argc, py_Ref argv) {
  170. PY_CHECK_ARGC(1);
  171. int res = py_next(argv);
  172. if(res == -1) return false;
  173. if(res) return true;
  174. return py_exception(tp_StopIteration, "");
  175. }
  176. static bool builtins_hash(int argc, py_Ref argv) {
  177. PY_CHECK_ARGC(1);
  178. py_i64 val;
  179. if(!py_hash(argv, &val)) return false;
  180. py_newint(py_retval(), val);
  181. return true;
  182. }
  183. static bool builtins_abs(int argc, py_Ref argv) {
  184. PY_CHECK_ARGC(1);
  185. return pk_callmagic(__abs__, 1, argv);
  186. }
  187. static bool builtins_divmod(int argc, py_Ref argv) {
  188. PY_CHECK_ARGC(2);
  189. return pk_callmagic(__divmod__, 2, argv);
  190. }
  191. static bool builtins_print(int argc, py_Ref argv) {
  192. int length;
  193. py_TValue* args = pk_arrayview(argv, &length);
  194. assert(args != NULL);
  195. c11_sv sep = py_tosv(py_arg(1));
  196. c11_sv end = py_tosv(py_arg(2));
  197. c11_sbuf buf;
  198. c11_sbuf__ctor(&buf);
  199. for(int i = 0; i < length; i++) {
  200. if(i > 0) c11_sbuf__write_sv(&buf, sep);
  201. if(!py_str(&args[i])) return false;
  202. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  203. }
  204. c11_sbuf__write_sv(&buf, end);
  205. c11_string* res = c11_sbuf__submit(&buf);
  206. pk_current_vm->print(res->data);
  207. c11_string__delete(res);
  208. py_newnone(py_retval());
  209. return true;
  210. }
  211. static bool builtins_exec(int argc, py_Ref argv) {
  212. PY_CHECK_ARGC(1);
  213. PY_CHECK_ARG_TYPE(0, tp_str);
  214. Frame* frame = pk_current_vm->top_frame;
  215. return py_exec(py_tostr(argv), "<exec>", EXEC_MODE, frame->module);
  216. }
  217. static bool builtins_eval(int argc, py_Ref argv) {
  218. PY_CHECK_ARGC(1);
  219. PY_CHECK_ARG_TYPE(0, tp_str);
  220. Frame* frame = pk_current_vm->top_frame;
  221. return py_exec(py_tostr(argv), "<eval>", EVAL_MODE, frame->module);
  222. }
  223. static bool builtins_isinstance(int argc, py_Ref argv) {
  224. PY_CHECK_ARGC(2);
  225. if(py_istuple(py_arg(1))) {
  226. int length = py_tuple_len(py_arg(1));
  227. for(int i = 0; i < length; i++) {
  228. py_Ref item = py_tuple_getitem(py_arg(1), i);
  229. if(!py_checktype(item, tp_type)) return false;
  230. if(py_isinstance(py_arg(0), py_totype(item))) {
  231. py_newbool(py_retval(), true);
  232. return true;
  233. }
  234. }
  235. py_newbool(py_retval(), false);
  236. return true;
  237. }
  238. if(!py_checktype(py_arg(1), tp_type)) return false;
  239. py_newbool(py_retval(), py_isinstance(py_arg(0), py_totype(py_arg(1))));
  240. return true;
  241. }
  242. static bool builtins_issubclass(int argc, py_Ref argv) {
  243. PY_CHECK_ARGC(2);
  244. if(!py_checktype(py_arg(0), tp_type)) return false;
  245. if(!py_checktype(py_arg(1), tp_type)) return false;
  246. py_newbool(py_retval(), py_issubclass(py_totype(py_arg(0)), py_totype(py_arg(1))));
  247. return true;
  248. }
  249. static bool builtins_getattr(int argc, py_Ref argv) {
  250. PY_CHECK_ARG_TYPE(1, tp_str);
  251. py_Name name = py_namev(py_tosv(py_arg(1)));
  252. if(argc == 2) {
  253. return py_getattr(py_arg(0), name);
  254. } else if(argc == 3) {
  255. py_StackRef p0 = py_peek(0);
  256. bool ok = py_getattr(py_arg(0), name);
  257. if(!ok && py_matchexc(tp_AttributeError)) {
  258. py_clearexc(p0);
  259. py_assign(py_retval(), py_arg(2));
  260. return true; // default value
  261. }
  262. return ok;
  263. } else {
  264. return TypeError("getattr() expected 2 or 3 arguments");
  265. }
  266. return true;
  267. }
  268. static bool builtins_setattr(int argc, py_Ref argv) {
  269. PY_CHECK_ARGC(3);
  270. PY_CHECK_ARG_TYPE(1, tp_str);
  271. py_Name name = py_namev(py_tosv(py_arg(1)));
  272. return py_setattr(py_arg(0), name, py_arg(2));
  273. }
  274. static bool builtins_hasattr(int argc, py_Ref argv) {
  275. PY_CHECK_ARGC(2);
  276. PY_CHECK_ARG_TYPE(1, tp_str);
  277. py_Name name = py_namev(py_tosv(py_arg(1)));
  278. py_StackRef p0 = py_peek(0);
  279. bool ok = py_getattr(py_arg(0), name);
  280. if(ok) {
  281. py_newbool(py_retval(), true);
  282. return true;
  283. }
  284. if(py_matchexc(tp_AttributeError)) {
  285. py_clearexc(p0);
  286. py_newbool(py_retval(), false);
  287. return true;
  288. }
  289. return false;
  290. }
  291. static bool builtins_delattr(int argc, py_Ref argv) {
  292. PY_CHECK_ARGC(2);
  293. PY_CHECK_ARG_TYPE(1, tp_str);
  294. py_Name name = py_namev(py_tosv(py_arg(1)));
  295. return py_delattr(py_arg(0), name);
  296. }
  297. static bool builtins_chr(int argc, py_Ref argv) {
  298. PY_CHECK_ARGC(1);
  299. PY_CHECK_ARG_TYPE(0, tp_int);
  300. py_i64 val = py_toint(py_arg(0));
  301. if(val < 0 || val > 128) { return ValueError("chr() arg not in range(128)"); }
  302. py_newstrn(py_retval(), (const char*)&val, 1);
  303. return true;
  304. }
  305. static bool builtins_ord(int argc, py_Ref argv) {
  306. PY_CHECK_ARGC(1);
  307. PY_CHECK_ARG_TYPE(0, tp_str);
  308. c11_sv sv = py_tosv(py_arg(0));
  309. if(sv.size != 1) {
  310. return TypeError("ord() expected a character, but string of length %d found", sv.size);
  311. }
  312. py_newint(py_retval(), sv.data[0]);
  313. return true;
  314. }
  315. static bool NoneType__repr__(int argc, py_Ref argv) {
  316. py_newstr(py_retval(), "None");
  317. return true;
  318. }
  319. static bool ellipsis__repr__(int argc, py_Ref argv) {
  320. py_newstr(py_retval(), "Ellipsis");
  321. return true;
  322. }
  323. static bool NotImplementedType__repr__(int argc, py_Ref argv) {
  324. py_newstr(py_retval(), "NotImplemented");
  325. return true;
  326. }
  327. py_TValue pk_builtins__register() {
  328. py_Ref builtins = py_newmodule("builtins");
  329. py_bindfunc(builtins, "repr", builtins_repr);
  330. py_bindfunc(builtins, "exit", builtins_exit);
  331. py_bindfunc(builtins, "len", builtins_len);
  332. py_bindfunc(builtins, "hex", builtins_hex);
  333. py_bindfunc(builtins, "iter", builtins_iter);
  334. py_bindfunc(builtins, "next", builtins_next);
  335. py_bindfunc(builtins, "hash", builtins_hash);
  336. py_bindfunc(builtins, "abs", builtins_abs);
  337. py_bindfunc(builtins, "divmod", builtins_divmod);
  338. py_bindfunc(builtins, "exec", builtins_exec);
  339. py_bindfunc(builtins, "eval", builtins_eval);
  340. py_bind(builtins, "print(*args, sep=' ', end='\\n')", builtins_print);
  341. py_bindfunc(builtins, "isinstance", builtins_isinstance);
  342. py_bindfunc(builtins, "issubclass", builtins_issubclass);
  343. py_bindfunc(builtins, "getattr", builtins_getattr);
  344. py_bindfunc(builtins, "setattr", builtins_setattr);
  345. py_bindfunc(builtins, "hasattr", builtins_hasattr);
  346. py_bindfunc(builtins, "delattr", builtins_delattr);
  347. py_bindfunc(builtins, "chr", builtins_chr);
  348. py_bindfunc(builtins, "ord", builtins_ord);
  349. // some patches
  350. py_bindmagic(tp_NoneType, __repr__, NoneType__repr__);
  351. py_bindmagic(tp_ellipsis, __repr__, ellipsis__repr__);
  352. py_bindmagic(tp_NotImplementedType, __repr__, NotImplementedType__repr__);
  353. return *builtins;
  354. }
  355. static bool function__closure__getter(int argc, py_Ref argv) {
  356. PY_CHECK_ARGC(1);
  357. Function* ud = py_touserdata(argv);
  358. if(!ud->closure) {
  359. py_newnone(py_retval());
  360. return true;
  361. }
  362. py_Ref r0 = py_pushtmp();
  363. py_Ref retval = py_pushtmp();
  364. py_newdict(retval);
  365. c11__foreach(NameDict_KV, ud->closure, it) {
  366. // printf("%s -> %s\n", py_name2str(it->key), py_tpname(it->value.type));
  367. py_newstr(r0, py_name2str(it->key));
  368. py_dict_setitem(retval, r0, &it->value);
  369. if(py_checkexc()) {
  370. py_shrink(2);
  371. return false;
  372. }
  373. }
  374. py_assign(py_retval(), retval);
  375. py_shrink(2);
  376. return true;
  377. }
  378. py_Type pk_function__register() {
  379. py_Type type =
  380. pk_newtype("function", tp_object, NULL, (void (*)(void*))Function__dtor, false, true);
  381. py_bindproperty(type, "__closure__", function__closure__getter, NULL);
  382. return type;
  383. }
  384. static bool nativefunc__repr__(int argc, py_Ref argv) {
  385. PY_CHECK_ARGC(1);
  386. py_newstr(py_retval(), "<nativefunc object>");
  387. return true;
  388. }
  389. py_Type pk_nativefunc__register() {
  390. py_Type type = pk_newtype("nativefunc", tp_object, NULL, NULL, false, true);
  391. py_bindmagic(type, __repr__, nativefunc__repr__);
  392. return type;
  393. }
  394. static bool super__new__(int argc, py_Ref argv) {
  395. py_Type* class_arg = py_newobject(py_retval(), tp_super, 1, sizeof(py_Type));
  396. Frame* frame = pk_current_vm->top_frame;
  397. *class_arg = 0;
  398. py_Ref self_arg = NULL;
  399. if(argc == 1) {
  400. // super()
  401. if(frame->has_function) {
  402. Function* func = py_touserdata(frame->p0);
  403. *class_arg = *(py_Type*)PyObject__userdata(func->clazz);
  404. if(frame->co->nlocals > 0) self_arg = &frame->locals[0];
  405. }
  406. if(class_arg == 0 || self_arg == NULL) return RuntimeError("super(): no arguments");
  407. } else if(argc == 3) {
  408. // super(type, obj)
  409. PY_CHECK_ARG_TYPE(1, tp_type);
  410. *class_arg = py_totype(py_arg(1));
  411. self_arg = py_arg(2);
  412. if(!py_isinstance(self_arg, *class_arg)) {
  413. return TypeError("super(type, obj): obj must be an instance of type");
  414. }
  415. } else {
  416. return TypeError("super() takes 0 or 2 arguments");
  417. }
  418. py_TypeInfo* types = pk_current_vm->types.data;
  419. *class_arg = types[*class_arg].base;
  420. if(*class_arg == 0) return RuntimeError("super(): base class is invalid");
  421. py_setslot(py_retval(), 0, self_arg);
  422. return true;
  423. }
  424. py_Type pk_super__register() {
  425. py_Type type = pk_newtype("super", tp_object, NULL, NULL, false, true);
  426. py_bindmagic(type, __new__, super__new__);
  427. return type;
  428. }